Score:1

bash change directory with spaces and backslash

ss flag

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...

jabbson avatar
sb flag
unless backslashes are actually a part of the folder name, try `TEST="MY DIRECTORY WITH STRANGE [CHARACTERS]"` and then `cd "$TEST"`
Score:1
us flag

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.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.