bash variable with spaces why cd "$myvar" results in one parameter, but myvar='"some stuff"' in two? [duplicate]

Solution 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