Tilde in path doesn't expand to home directory

Benjamin picture Benjamin · Apr 21, 2011 · Viewed 10.9k times · Source

Say I have a folder called Foo located in /home/user/ (my /home/user also being represented by ~).

I want to have a variable

a="~/Foo" and then do

cd $a

I get -bash: cd: ~/Foo: No such file or directory

However if I just do cd ~/Foo it works fine. Any clue on how to get this to work?

Answer

bmk picture bmk · Apr 21, 2011

You can do (without quotes during variable assignment):

a=~/Foo
cd "$a"

But in this case the variable $a will not store ~/Foo but the expanded form /home/user/Foo. Or you could use eval:

a="~/Foo"
eval cd "$a"