Variable Substitution

In the following substitutions, braces ({ }) are optional, except when needed to separate a variable name from following characters that would otherwise be considered part of the name.

Table 5-22. Substitution variables

Variable

Meaning

${var}

Value of variable var.

$0

Name of the program.

${n}

Individual arguments on command line (positional parameters); 1 n 9.

$#

Number of arguments on command line.

$*

All arguments on command line.

$@

Same as $*, but contents are split into words when the variable is enclosed in double quotes.

$$

Process number of current shell; useful as part of a filename for creating temporary files with unique names.

$?

Exit status of last command (normally 0 for success).

$!

Process number of most recently issued background command.

$-

Current execution options (see the set built-in command). By default, hB for scripts and himBH for interactive shells.

$_

Initially set to name of file invoked for this shell, then set for each command to the last word of the previous command.

Tables 5-23 through Table 5-25 show various types of operators that can be used with bash variables.

Table 5-23. Substitution operators

Operator

Substitution

${varname:-word}

If varname exists and isn’t null, return its value; otherwise, return word.

 

Purpose: Returning a default value if the variable is undefined.

 

Example: ${count:-0} evaluates to 0 if count is undefined.

${varname:=word}

If varname exists and ...

Get Mac OS X Tiger in a Nutshell 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.