Читать книгу Linux Bible - Christopher Negus - Страница 202
Parameter expansion in bash
ОглавлениеAs mentioned earlier, if you want the value of a variable, you precede it with a $
(for example, $CITY
). This is really just shorthand for the notation ${CITY}
; curly braces are used when the value of the parameter needs to be placed next to other text without a space. Bash has special rules that allow you to expand the value of a variable in different ways. Going into all of the rules is probably overkill for a quick introduction to shell scripts, but the following list presents some common constructs you're likely to see in bash scripts that you find on your Linux system.
${var:-value}: If variable is unset or empty, expand this to value.
${var#pattern}: Chop the shortest match for pattern from the front of var's value.
${var##pattern}: Chop the longest match for pattern from the front of var's value.
${var%pattern}: Chop the shortest match for pattern from the end of var's value.
${var%%pattern}: Chop the longest match for pattern from the end of var's value.
Try typing the following commands from a shell to test how parameter expansion works:
$ THIS="Example" $ THIS=${THIS:-"Not Set"} $ THAT=${THAT:-"Not Set"} $ echo $THIS Example $ echo $THAT Not Set
In the examples here, the THIS
variable is initially set to the word Example
. In the next two lines, the THIS
and THAT
variables are set to their current values or to Not Set
, if they are not currently set. Notice that because I just set THIS
to the string Example
, when I echo the value of THIS
it appears as Example
. However, because THAT
was not set, it appears as Not Set
.