Search code examples
bashcd

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?


Solution

  • 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 "~"`