0

Why is the following wrong?

$ cd "~/my data"
bash: cd: ~/my data: No such file or directory

$ cd ~"/my data"
bash: cd: ~/my data: No such file or directory

$ cd ~/"my data" # works
2

That how bash tilde expansion works:

If a word begins with an unquoted tilde character (‘~’), all of the characters up to the first unquoted slash (or all characters, if there is no unquoted slash) are considered a tilde-prefix.


Lets assume your home directory is /home/user and you're currently in it, the first example:

cd "~/my data"

This tries to cd into a directory with the path /home/user/~/my data/. Notice that ~ is a valid character in directory or file names.


The second example:

cd ~"/my data"

This does the same as the first. If your wonder, it's because the slash is quoted, as stated in the citation above.


The third example:

cd ~/"my data"

This does tilde expansion, because the slash is not quoted, and is therefore replaced by the contents of the $HOME environment variable. This changes to the directory /home/user/my data/.

| improve this answer | |
  • thanks. In the first example, is it ./~/my data/ rather than /home/user/~/my data/? – Tim Dec 5 '15 at 14:45
  • @Tim Yes, from that directory you're in it's ./~/my data. I wrote the absolute path in the answer. – chaos Dec 5 '15 at 15:21
  • "all of the characters up to the first unquoted slash" does not include the first unquoted slash, correct? – Tim Dec 5 '15 at 16:06
  • @Tim Correct, see the link in the question for tilde-prefixes. – chaos Dec 6 '15 at 18:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.