Tilde Expansion and Wildcards

The shell does two different expansions related to filenames. The first is tilde expansion, and the second is variously termed wildcard expansion, globbing, or pathname expansion.

Tilde Expansion

The shell performs tilde expansion if the first character of a command-line string is a tilde (~), or if the first character after any unquoted colon in the value of a variable assignment (such as for the PATH or CDPATH variables) is a tilde.

The purpose of tilde expansion is to replace a symbolic representation for a user's home directory with the actual path to that directory. The user may be named either explicitly, or implicitly, in which case it is the current user running the program:

$ vi ~/.profile            
               Same as vi $HOME/.profile
$ vi ~tolstoy/.profile     
               Edit user tolstoy's .profile file

In the first case, the shell replaces the ~ with $HOME, the current user's home directory. In the second case, the shell looks up user tolstoy in the system's password database, and replaces ~tolstoy with tolstoy's home directory, whatever that may be.

Tip

Tilde expansion first appeared in the Berkeley C shell, csh. It was intended primarily as an interactive feature. It proved to be very popular, and was adopted by the Korn shell, bash, and just about every other modern Bourne-style shell. It thus also found its way into the POSIX standard.

However (and there's always a "however"), many commercial Unix Bourne shells don't support it. Thus, you should not use tilde expansion inside ...

Get Classic Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.