Why doesn't this command work: cd `echo -n" ~ "`
The problem is that bash doesn't do any additional expansion after command substitution. So while it cd ~
expands as you want it cd $(echo '~')
doesn't work.
There is a keyword eval
created for this kind of situation - it forces you to expand (evaluate) the command line again. If you use eval
on this line, it forces it to ~
be expanded to the user's directory, even if the normal time for expansion has already passed. (As it ~
doesn't exist until the echo command is run, at which point it's too late for expansion.)
eval cd `echo -n "~"`
source to share
If you do cd ~
, the shell expands ~
to your home directory before executing the command. But if you use double quotes ( "~"
), then it is taken as a literal string and not expanded.
You can see the difference:
$ echo ~
/home/username
$ echo "~"
~
In order to have ~
it expanded by the shell, you need to remove the double quotes.
The lurking behavior of double quotes is documented in the Bash manual: http://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html
source to share
You also get the same problem if you just do cd "~"
:
$ cd "~"
bash: cd: ~: No such file or directory
cd
doesn't understand what ~
is special. He tries and fails to find a directory that is literally named ~
.
The reason it works cd ~
is because it is bash
editing the command before running it. bash
replaces cd ~
with cd $HOME
and then expands $HOME
to get cd /home/YourUsername
.
Thus,
cd `echo -n "~"`
becomes
cd "~"
source to share