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 

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.


@jw013 has given a valid explanation and solution.

But there may be some cases when you do want to quote the paths, e.g. when they contain multiple spaces or special symbols. In this case you should use $HOME instead of ~, i.e. your BASE="~/z" will become BASE="$HOME/z" and work correctly, because parameter substitution is interpreted in double quotes, unlike tilde expansion.

  • 5
    That's one way to do it, but it is not necessary. BASE=~/"quoted name" works just fine, so long as the ~ is left unquoted. – hvd Nov 23 '14 at 20:56
  • 4
    @hvd: you actually have to leave the slash unquoted as well. BASE=~/"quoted name" works, but BASE=~"/quoted name" doesn't. – Gordon Davisson Nov 24 '14 at 7:20
  • You're right. Good catch. – hvd Nov 24 '14 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.