Tilde in path doesn't expand to home directory Tilde in path doesn't expand to home directory bash bash

Tilde in path doesn't expand to home directory


You can do (without quotes during variable assignment):

a=~/Foocd "$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"


You can use $HOME instead of the tilde (the tilde is expanded by the shell to the contents of $HOME).Example:

dir="$HOME/Foo";cd "$dir";


Although this question is merely asking for a workaround, this is listed as the duplicate of many questions that are asking why this happens, so I think it's worth giving an explanation. According to https://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap02.html#tag_18_06:

The order of word expansion shall be as follows:

Tilde expansion, parameter expansion, command substitution, and arithmetic expansion shall be performed, beginning to end.

When the shell evaluates the string cd $a, it first performs tilde expansion (which is a no-op, since $a does not contain a tilde), then it expands $a to the string ~/Foo, which is the string that is finally passed as the argument to cd.