Linux Command Reference ยท Bash Syntax
Bash tilde expansion
Reference for Bash tilde expansion: how ~ becomes your home directory, ~user, ~+ and ~- for the current and previous directory, and when quoting stops it.
Tilde expansion replaces a leading ~ with a directory name. On its own, ~ means your home directory. ~alice means the home directory of the user alice. The shell does this before the command runs, so the program receives a plain path.
It only works at the start of a word (or right after : or = in assignments such as PATH), and it never happens inside quotes.
cd ~ ls ~/Documents echo ~root
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.
Syntax
~ ~/path
~user ~user/path
~+ ~-
~N ~+N ~-N
| Form | Expands to |
|---|---|
~ |
The value of HOME. If HOME is unset, the home directory of the current user from the password database. |
~user |
The home directory of user. |
~+ |
The value of PWD, the current directory. |
~- |
The value of OLDPWD, the previous directory (the one cd - returns to). |
~N, ~+N, ~-N |
An entry of the directory stack as shown by dirs (~N and ~+N count from the top, ~-N from the bottom). |
Returns: the directory path with no trailing slash. Edge cases: if the user does not exist, or OLDPWD is unset, the word is left unchanged.
Usage notes
- Never in quotes.
"~/file"is a file named~inside the current directory'sfile. Write~/"my file"or"$HOME/my file". - A variable holding a tilde is not expanded when you later use it unquoted in most places:
x="~/a"; ls $xfails. Store$HOME/ainstead, or useevalonly in controlled cases. - Assignments are special:
PATH=~/bin:$PATHexpands the tilde because it follows=;PATH="~/bin:$PATH"does not. - Scripts that run as another user (cron, sudo) may have a different or missing
HOME. Rely on explicit paths for important files. - Prefer
$HOMEin portable scripts;~is standard in POSIX shells but~+,~-and~Nare Bash features. - Tilde is not a glob.
~/*.txtworks because the tilde expands first and the glob then applies. See globbing. - Quote everything after the tilde if names contain spaces:
cd ~/"My Documents". cd ~-is the same ascd -but does not print the new directory.