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?
If you use double quotes the ~ will be kept as that character in $a.
cd $a will not expand the ~ since variable values are not expanded by the shell.
The solution is:
eval "cd $a"
You can use
$HOME
instead of the tilde (the tilde is expanded by the shell to the contents of$HOME
). Example:A much more robust solution would be to use something like sed or even better, bash parameter expansion:
or if you must use sed,
You can do (without quotes during variable assignment):
But in this case the variable
$a
will not store~/Foo
but the expanded form/home/user/Foo
. Or you could useeval
: