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
Tim
  • 101,790

1 Answers1

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/.

chaos
  • 48,171
  • thanks. In the first example, is it ./~/my data/ rather than /home/user/~/my data/? – Tim Dec 05 '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 05 '15 at 15:21
  • "all of the characters up to the first unquoted slash" does not include the first unquoted slash, correct? – Tim Dec 05 '15 at 16:06
  • @Tim Correct, see the link in the question for tilde-prefixes. – chaos Dec 06 '15 at 18:34