Shell Expansion


Tilde Expansion

The tilde (~) expands to a directory. Which directory depends on what, if any, characters follow it.

Tilde Prefix

Expansion

~

$HOME

~/foo

$HOME/foo

~me/foo

subdirectory foo within the home directory of user me

~+/foo

$PWD/foo

~-/foo

if $OLDPWD is set, $OLDPWD/foo

~N

for an integer N, the Nth element in the directory stack (dirs +N)

~+N

for an integer N, the Nth element in the directory stack (dirs +N)

~-N

for an integer N, the -Nth element in the directory stack (dirs -N)


Parameter Expansion

The simplest form of parameter expansion is ${parameter}.

Conditional Parameter Expansion

Conditional parameter expansions provide default values if the parameter is unset or empty.

Suppose that:

export a=a
export b=
unset c

Operator

Parameter Expansion

Value

Side Effects

:-

${a:-d}

a

:-

${b:-d}

d

:-

${c:-d}

d

-

${a-d}

a

-

${b-d}

-

${c-d}

d

:=

${a:=d}

a

:=

${b:=d}

d

b is set to d

:=

${c:=d}

d

c is set to d

=

${a=d}

a

=

${b=d}

=

${c=d}

d

c is set to d

:?

${a:?d}

a

:?

${b:?d}

d

shell exits

:?

${c:?d}

d

shell exits

?

${a?d}

a

?

${b?d}

?

${c?d}

d

shell exits

:+

${a:+d}

d

:+

${b:+d}

:+

${c:+d}

+

${a+d}

d

+

${b+d}

d

+

${c+d}

The general rules are that:


Command Expansion

$(date) expands to the output of date.

The commands are executed in a subshell, so all side-effects are discarded.

Command expansion can be nested.


Arithmetic Expansion

$(( 1 + 1 )) expands to 2. For a description of all arithmetic operators, see here.

The tokens within an arithmetic expansion undergo all of the above and below expansions individually. Arithmetic expansion can be nested.

Variables are expanded, though an empty or unset variable expands to 0. If $x expands to a valid number, then $(($x+1)) and $((x+1)) are equivalent.

A string literal will not expand, and in fact will raise an error.


Word Splitting

A command is split into tokens using $IFS. (The default is spaces, tabs, and newlines.) Leading and trailing instances of $IFS are ignored. Repeated instances of any member of $IFS are treated as a singular delimiter for splitting.

Literal null tokens ("" or '') are kept and passed to commands. On the other hand, unquoted null tokens (as resulting from expansions) are removed. The exception is if such an expansion happens within double quotes (such as "$var"), in which case a null token is kept. Note that when such an expansion is part of a larger, non-null token (such as "x$var"), the null expansion part is removed.


Filename Expansion

The unquoted characters *, ?, and [ trigger filename expansion.

* matches any 0 or more characters.

? matches any 1 character.

[...] matches any character contained within the brackets, except if a forward slash (/) is included.


CategoryRicottone

Shell/Expansion (last edited 2023-01-25 07:42:04 by DominicRicottone)