1

I'm trying to build a script that I need to be quite able to manage directory with spaces or/and backslashes in their name or not.

Inside a bash script or directly on bash shell using variables for testing, I cannot change to a directory with escaped spaces in it, I can do it manually, but if I put it in a variable and I try to change directory using that variable I cannot.

EXAMPLE:

directory I want to cd to :

MY\ DIRECTORY\ WITH\ STRANGE\ \[CHARACTERS\]

in bash prompt I can cd to it :

cd MY\ DIRECTORY\ WITH\ STRANGE\ \[CHARACTERS\]

but if I put the director name in a variable I cannot :

TEST="MY\ DIRECTORY\ WITH\ STRANGE\ \[CHARACTERS\]"

cd "$TEST"

-bash: cd:MY\ DIRECTORY\ WITH\ STRANGE\ \[CHARACTERS\]: no such file or directory

So, is there a way to handle backslash in bash shell in a clean transparent way ?

I could remove backslashes from the string, but that introduce some tricky variable expand problems with directory names...

SimoneM
  • 121
  • 1
  • unless backslashes are actually a part of the folder name, try `TEST="MY DIRECTORY WITH STRANGE [CHARACTERS]"` and then `cd "$TEST"` – jabbson Nov 10 '22 at 23:07

1 Answers1

1

If you insist on using backslashed directory name in $TEST, you could try:

cd "${TEST//\\/}"

Explanation from man bash under the "Parameter Expansion" section:

${parameter/pattern/string}

Pattern substitution. The pattern is expanded to produce a pattern just as in pathname expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. If pattern begins with /, all matches of pattern are replaced with string. Normally only the first match is replaced. ...

In other words, we are replacing "all matches" (//) of backslash \\ (because we need to escape the backslash) with an empty character.

But if you could remove the backslashes from the variable name, then what you were trying to do will work:

TEST="MY DIRECTORY WITH STRANGE [CHARACTERS]"
cd "$TEST"

BTW, the previously mentioned cd "${TEST//\\/}" command executes precisely the same string as mentioned here.

Srinidhi
  • 111
  • 3