bash - How to cd into a directory with space in the name? -


i tried lot of things. see below:

attempt directory: /cygdrive/c/users/my dir/documents

$ docs="/cygdrive/c/users/my\ dir/documents"  $ echo $docs /cygdrive/c/users/my\ dir/documents  $ cd $docs -bash: cd: /cygdrive/c/users/my\: no such file or directory  $ cd /cygdrive/c/users/my\ dir/documents (success) 

very weird behaviour. when manually type in, backspace escape character thing. not when use parameter expansion variable docs.
tried other variations such no backslash.

$ docs=/cygdrive/c/users/rahman\ dir/documents  $ echo $docs /cygdrive/c/users/my dir/documents  $ cd $docs -bash: cd: /cygdrive/c/users/my: no such file or directory 

or

$ docs="/cygdrive/c/users/my dir/documents"  $ echo $docs /cygdrive/c/users/my dir/documents  $ cd $docs -bash: cd: /cygdrive/c/users/my: no such file or directory 

i know possible. see here:

$ echo $home /home/my dir 

[edit] pointed out, cd $home doesn't work either. quotes must put around it.

what heck:

$ docs="\"/cygdrive/c/users/my dir/documents\""  $ echo $docs "/cygdrive/c/users/my dir/documents"  $ cd $docs -bash: cd: "/cygdrive/c/users/my: no such file or directory 

$ cd "$docs" 

you need quote "$docs" prevent spaces being parsed word separators. more not, variable references should quoted.

note $home have same problem. issue coming when shell evaluates variable references; it's nothing variables use or how assign them. it's expansion needs quoted.

$ echo $home /home/my dir 

this deceptive. echo echoing 2 strings /home/my , dir. if use cd or ls you'll see how it's working.

$ ls $home ls: cannot access /home/my: no such file or directory ls: cannot access dir: no such file or directory $ cd $home bash: cd: /home/my: no such file or directory $ cd "$home" <success!> 

can ask why works when manually type in not in variable?

great question! let's examine commands typed:

$ docs="\"/cygdrive/c/users/my dir/documents\"" $ echo $docs "/cygdrive/c/users/my dir/documents" $ cd $docs -bash: cd: "/cygdrive/c/users/my: no such file or directory 

the reason doesn't work because bash doesn't parse quotes inside variable expansions. does perform word splitting, whitespace in unquoted variable expansions taken word separators. doesn't parse quotes in way, meaning can't put double quotes inside variable override word splitting.

$ cd $docs 

because of this, cd passed 2 parameters. far cd knows looks wrote:

$ cd '"/cygdrive/c/users/my' 'dir/documents"' 

two parameters, double quotes intact.


Comments

Popular posts from this blog

java - JavaFX 2 slider labelFormatter not being used -

Detect support for Shoutcast ICY MP3 without navigator.userAgent in Firefox? -

web - SVG not rendering properly in Firefox -