Bash - Tilde (~) Expansion

> Procedural Languages > Bash Shell and (Unix|Linux) Utilities (XCU)

1 - About

The tilde expansion replaces the tilde with a value which is dependent of the syntax.

If the tilde expansion fails, the word is unchanged.

Advertising

3 - Syntax

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.

~TildePrefix/

There is three forms of prefix:

  • A login name
  • A + or - (PWD or OLDPWD)
  • An integer with + or -. Ie an element in the directory stack.

3.1 - Login Name

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.
  • Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name.

If the login name is invalid, the word is unchanged.

Example:

  • Tilde with login name (deamon)
echo ~daemon/test
/usr/sbin/test

The HOME is defined in the file /etc/passwd

Advertising

3.2 - ~[+-]

If the tilde-prefix is a:

  • ~+, the value of the shell variable PWD replaces the tilde-prefix.
  • ~-, the value of the shell variable OLDPWD, if it is set, is substituted.

For the variable, PWD and OLDPWD, see Bash - (Current|Working) Directory

Example:

echo ~+
echo ~-

3.3 - ~N[+-]

If the characters following the tilde in the tilde-prefix consist of a number N, optionally prefixed by a ‘+’ or a ‘-’, the tilde-prefix is replaced with the corresponding element from the directory stack, as it would be displayed by the dirs builtin invoked with the tilde-prefix as an argument.

If the characters following the tilde in the tilde-prefix consist of a number without a leading + or -, + is assumed.

Example:

dirs
/root /
echo ~0
/root
echo ~1
/
Advertising

4 - Management

4.1 - variable assignment

Each variable assignment is checked for unquoted tilde-prefixes immediately following a : or the first =. In these cases, tilde expansion is also performed.

Consequently, one may use file names with tildes in assignments to:

  • PATH,
  • MAILPATH,
  • and CDPATH,

and the shell assigns the expanded value.