This is a bash
feature called Tilde Expansion. Citing man bash
:
If a word begins with an unquoted tilde character (`~'), all of the
characters preceding the first unquoted slash (or all characters, if
there is no unquoted slash) are considered a tilde-prefix. If none of
the characters in the tilde-prefix are quoted, the characters in the
tilde-prefix following the tilde are treated as a possible login name.
If this login name is the null string, the tilde is replaced with the
value of the shell parameter HOME. If HOME is unset, the home
directory of the user executing the shell is substituted instead.
For the expansion to work the tilde character ~
needs to be unquoted, else the character is taken literally and cd
fails if there is no directory named ~
present in the current directory. See this entensive answer for an explanation of quoting in bash
. If you need to quote part of the path, you can therefore:
quote at least the characters that need quoting with single quotes, e.g.
~/dir' 'with' 'spaces/
or
~/'dir with spaces/'
quote at least the characters that need quoting with double quotes, e.g.
~/dir" "with" "spaces/
or
~/"dir with spaces/"
quote only the characters that need quoting with backslashes , e.g.
~/dir\ with\ spaces/
Tilde Expansion has some more interesting features, e.g.:
~+
expands to the value of PWD
, i.e. the current working directory
~-
expands to the value of OLDPWD
, i.e. the previous working directory
~john
expands to the home directory associated with the login name “john”
cd
into a directory named~
?cd
alltogether. Use variables to store pathnames you don't want to type multiple times, e.g.pf=~/.wine/drive_c/Program\ Files/; cp /path/to/file "$pf"
/
orNUL
?cd ./~