Skip to content
Tutorials Center
My learning

Topics

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.

Terminal
cd ~
ls ~/Documents
echo ~root

Try it

Bash The common forms

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.

Bash Where tilde expansion does not happen

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

Terminal
~            ~/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's file. 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 $x fails. Store $HOME/a instead, or use eval only in controlled cases.
  • Assignments are special: PATH=~/bin:$PATH expands 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 $HOME in portable scripts; ~ is standard in POSIX shells but ~+, ~- and ~N are Bash features.
  • Tilde is not a glob. ~/*.txt works 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 as cd - but does not print the new directory.