Ubuntu – Why can’t I cd to a quoted tilde (‘~’)

bashcommand line

Writing my first script so I'm sure this is a basic question, but can someone please explain to me why I can:

cd ~
cd bin
cd ~/bin
cd 'bin'

But not

cd '~'
cd '~/bin'

I need to cd to a directory path with a space in one of the directory names, so I need the quotes (it's Windows Program Files under wine). I can get around it with two cd commands, but why can't I put ~ in quotes?

If I type cd '~' (or cd "~") I get:

bash: cd: ~: No such file or directory

Best Answer

As @karel noted in his answer, ~ is a special character and expanded by Bash into the current user's home directory. See Bash's manual on "Tilde Expansion", or search for the headline "Tilde Expansion" in the man page (man bash).

Any kind of quotation around the ~ prevents this tilde expansion.


To answer your question about how you still can use it to cd into a directory with spaces in its name, there are a few alternatives:

  • Omit quotes and escape the spaces with backslashes instead:

    cd ~/foo/spaces\ are\ cool/bar
    
  • Quote the rest of the path, but omit them around the tilde and the first slash:

    cd ~/"foo/spaces are cool/bar"
    

    As you see, you can concatenate quoted and unquoted strings in Bash by simply writing them next to each other without any spaces in between.

  • Use the environment variable $HOME instead of the tilde, which still gets expanded inside "double quotes" (but not 'single quotes'):

    cd "$HOME/foo/spaces are cool/bar"