Eugen Konkov
Eugen Konkov

Reputation: 25187

why this command does not work: cd `echo -n "~"`

Running the command

cd \`echo -n "~"\`

I get the following error:

bash: cd: ~: No such file or directory

What's the problem if 'cd ~' works fine?

Upvotes: 3

Views: 284

Answers (3)

piojo
piojo

Reputation: 6723

The issue is that bash does not do an additional expansion after command substitution. So while cd ~ is expanded the way you want, cd $(echo '~') does not.

There is a keyword called eval that was created for this sort of situation--it forces the command line to be expanded (evaluated) again. If you use eval on that line, it forces the ~ to be expanded into the user directory, even though the normal time for expansion has already passed. (Because the ~ does not exist until the echo command is run, and at that point, it's too late for expansion.)

eval cd `echo -n "~"`

Upvotes: 4

Aaron McDaid
Aaron McDaid

Reputation: 27143

You will also get the same issue if you simply do cd "~":

$ cd "~"
bash: cd: ~: No such file or directory

cd doesn't understand that ~ is special. It tries, and fails, to find a directory literally called ~.

The reason that cd ~ works is that bash edits the command before running it. bash replaces cd ~ with cd $HOME, and then expands $HOME to get cd /home/YourUsername.

Therefore,

cd `echo -n "~"`

becomes

cd "~"

Upvotes: 0

Grodriguez
Grodriguez

Reputation: 21995

If you do cd ~, the shell expands ~ to your home directory before executing the command. But if you use double quotes ("~"), then this is taken as a literal string and not expanded.

You can see the difference:

$ echo ~
/home/username
$ echo "~"
~

In order to have ~ expanded by the shell, you need to remove the double quotes.

The escaping behaviour of double quotes is described in the Bash manual: http://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html

Upvotes: 4

Related Questions