Bash: Expansion operators
Parameter expansion
It is the process by which the shell provides the value of a variable for use in the program. The simplest form is:
a="Hello"
echo $a
The shell has more complicated forms, all of which enclose the variable’s name in braces ${variable} and then add additional syntax telling the shell what to do. But braces by themselves are also useful, for example, when you need to follow a variable name with a character that might be otherwise be interpreted as part of the name:
a=3
echo "I live in the ${a}rd floor." # OK
echo "I live in the $ard floor." # Not OK
Expansion operators
Substitution operators
| Operator | Substitution |
|---|---|
| ${varname:-word} | If varname exists and isn’t null, return its value; otherwise, return word. |
| Return a default value if the variable is undefined. | |
| ${varname:=word} | If varname exists and isn’t null, return its value; otherwise, set it to word and return its value. |
| Set a variable to a default value if it is undefined. | |
| ${varname:+word} | If varname exists and isn’t null, return word; otherwise, return null. |
| Test for the existence of a variable. |
Pattern-matching operators
| Operator | Substitution |
|---|---|
| ${varname#pattern} | If the pattern matches the beginning, delete the shortest match and return the rest. Delete prefix ; Non-greedy. |
| ${varname##pattern} | If the pattern matches the beginning, delete the longest match and return the rest. Delete prefix ; Greedy. |
| ${varname%pattern} | If the pattern matches the end, delete the shortest match and return the rest. Delete suffix ; Non-greedy. |
| ${varname%%pattern} | If the pattern matches the end, delete the longest match and return the rest. Delete suffix ; Greedy. |
Positional parameters
$#: Total number of arguments passed to the shell script or function.
$*/$@: All positional arguments at once.
"$*": All postitional arguments as a single string.
"$@": All positional arguments as separate strings.
$_: Last argument of the previous command.
Example
What is the output depending on the option used to iterate over arguments for this code?
file: args.sh
-------------
for arg in <OPTION>
do
printf "Arg: $arg\n"
done
_$: ./args.sh 1 "2 3"
Output for different values of <OPTION>:
| $* | $@ | ”$*” | ”$@” |
|---|---|---|---|
| Arg: 1 | Arg: 1 | Arg: 1 2 3 | Arg: 1 |
| Arg: 2 | Arg: 2 | Arg: 2 3 | |
| Arg: 3 | Arg: 3 |