0

I'm struggling to understand why following does not work as expected in bash:

$ myvar='"some stuff"'
$ echo $myvar
"some stuff"
$ cd $myvar
bash: cd: "some: No such file or directory

I know the canonical way is to (How to use cd with shell variable containing spaces):

$ myvar="some stuff"
$ echo $myvar
some stuff
$ cd "$myvar"

But e.g. here https://stackoverflow.com/a/12258418/881191 answer by Alex for macOS advices to escape quotations, which I also tried and it's the same as putting double quotations inside single ones in my case. Why in one case cd gets two parameters and in other two from as I see it same "some stuff"?

  • 1
    The shell parses quotes and escapes before expanding variable references, so if you put a quote in a variable, by the time it's part of the command it's too late for it to work normally. See: Why does shell ignore quotes in arguments passed to it through variables? BTW, the reason embedding quotes worked in the answer you linked is that that's an alias, not a variable, and quotes do get parsed after aliases are expanded. – Gordon Davisson Oct 7 '19 at 6:43
  • @ Gordon, thank you! will you write it as answer so I can upvote? – Alexei Martianov Oct 7 '19 at 6:56
  • This part of shell syntax confuses a lot of people, so there are are a lot of questions about it already. Lots are on stackoverflow (e.g. this one), and a few here on AskDifferent as well (this and this), so I think it's better to mark this as a duplicate question. – Gordon Davisson Oct 7 '19 at 18:11
1

Typically, quotes are strip in a parameter/variable assignment, unless the quotes them self are quoted and they then become part of the string. As in your example "some stuff" is the string attached to $myvar. When you issue the command-

cd $myvar

the command is broken up into tokens- words and operators. The shell parses them into a command and arguments, then parameter/variable expansion takes place on $myvar. Since $myvar isn't quoted the contents are split into two words (known as field or word splitting) -

"some and stuff"

Thus, the error message- bash: cd: "some: No such file or directory. Since cd only accepts one argument stuff" is disregarded. Even when you quote the variable $myvar it still produces an error message because the directory name is some stuff not "some stuff"-

cd "$myvar" 
bash: cd: "some stuff": No such file or directory  
| improve this answer | |

Not the answer you're looking for? Browse other questions tagged .