1. Overview

The ~ (tilde) character has a special meaning in Linux. Many users use this character to address files or directories in their user’s homes. This, however, is not its only use. In this tutorial, we’ll have a look at the Bash feature called tilde expansion. Because tilde expansion is a feature of the shell and not the operating system, implementation varies between shells. All examples in this article are specific to the Bash shell.

2. Our User Home

As mentioned in the overview section, ~ is best known for expanding to a user’s home directory. No matter where we are on our file system, we can always return to our home directory by running:

$ cd ~

We can actually fetch the home directory from the $HOME environment variable. Therefore, the statement above is equivalent to:

$ cd $HOME

We can even change the value of $HOME and make it point to wherever we want. For example:

$ export HOME=/tmp
$ cd ~
$ pwd
/tmp

3. Other Users’ Homes

Adding a username to ~ will expand it to the home directory of this specific user. For example, if we would like to cd into Alice’s home directory, we’d run:

$ cd ~alice

Obviously, we can’t fetch this information from $HOME. Instead, Bash’s tilde expansion retrieves this information from the password database using the getpwent() function.

4. Working Directories

Tilde expansion can also be used to resolve the current or previous working directory. We can expand ~ to our current working directory by adding + (plus):

$ cd /tmp
$ echo ~+
/tmp

Similarly, the – (minus) sign expands to the previous working directory:

$ cd /etc
$ echo ~-
/tmp

Both current and previous working directories are taken from the $PWD and $OLDPWD environment variables, respectively.

5. The Directory Stack

Finally, we can also use ~ to refer to directories on the directory stack. The directory stack in Bash is a list of recently visited directories that can be manipulated by using the pushd and popd commands. Imagine at one point our directory stack looks like:

$ dirs
/bin /dev /etc /home /lib /opt /var /

Using ~ and an index number, we can refer to each entry in the directory stack from left to right, starting from 0 (zero):

$ echo ~0
/bin
$ echo ~1
/dev
$ echo ~6
/

By prefixing our index with a minus sign, we traverse the stack from right to left:

$ echo ~-0
/
$ echo ~-1
/opt
$ echo ~-6
/bin

6. Conclusion

In this article, we learned the meaning of the ~ character and how tilde expansion works in Bash. We use it to refer to a user’s home directory, current and previous working directories, and even entries on the directory stack. The tilde expansion depicted in this article is specific to Bash. In other shells, tilde expansion might be less sophisticated.