Previous: Tilde Expansion, Up: Word Expansion
Part of ordinary shell syntax is the use of `$variable' to substitute the value of a shell variable into a command. This is called variable substitution, and it is one part of doing word expansion.
There are two basic ways you can write a variable reference for substitution:
${
variable}
$
variablefoo
and expands
into `tractor-bar'.
When you use braces, you can also use various constructs to modify the value that is substituted, or test it in various ways.
${
variable:-
default}
${
variable:=
default}
${
variable:?
message}
Otherwise, print message as an error message on the standard error
stream, and consider word expansion a failure.
${
variable:+
replacement}
${#
variable}
These variants of variable substitution let you remove part of the variable's value before substituting it. The prefix and suffix are not mere strings; they are wildcard patterns, just like the patterns that you use to match multiple file names. But in this context, they match against parts of the variable value rather than against file names.
${
variable%%
suffix}
If there is more than one alternative for how to match against suffix, this construct uses the longest possible match.
Thus, `${foo%%r*}' substitutes `t', because the largest
match for `r*' at the end of `tractor' is `ractor'.
${
variable%
suffix}
If there is more than one alternative for how to match against suffix, this construct uses the shortest possible alternative.
Thus, `${foo%%r*}' substitutes `tracto', because the shortest
match for `r*' at the end of `tractor' is just `r'.
${
variable##
prefix}
If there is more than one alternative for how to match against prefix, this construct uses the longest possible match.
Thus, `${foo%%r*}' substitutes `t', because the largest
match for `r*' at the end of `tractor' is `ractor'.
${
variable#
prefix}
If there is more than one alternative for how to match against prefix, this construct uses the shortest possible alternative.
Thus, `${foo%%r*}' substitutes `tracto', because the shortest match for `r*' at the end of `tractor' is just `r'.