Bash – How to variables use “~” for cd’ing

bashcd-commandquotingshellvariable

How can I use a variable – $BASE in my cd.
I tried the following but I get an error

$ cd ~/z/repo_1_ruby_193/
23:23:57 durrantm Castle2012 /home/durrantm/z/repo_1_ruby_193 

$ BASE="~/z"
23:24:03 durrantm Castle2012 /home/durrantm/z/repo_1_ruby_193 

$ cd $BASE/repo_1_ruby_193
-bash: cd: ~/z/repo_1_ruby_193: No such file or directory
23:24:25 durrantm Castle2012 /home/durrantm/z/repo_1_ruby_193 

Best Answer

In cd ~/z/ you are using Tilde expansion to expand ~ into your home directory. In BASE="~/z", you are not because you quoted the ~ character, so it is not expanded. That is why you get a message complaining about a nonexistent ~ directory. The solution is to not quote it, i.e. BASE=~/z in order to let the expansion occur.

Related Question