2. Variable expansions
-
We have already seen that sometimes we need to surround variable names in braces, to avoid any confusion:
a="foo"
echo "$a_file"
echo "${a}_file"
-
Get a default value if the variable is unset (or empty):
${parameter:-word}
foo=
echo ${foo:-"substitute value if unset"}
echo $foo
foo=bar
echo ${foo:-"substitute value if unset"}
echo $foo
-
Assign a default value if the variable is unset (or empty):
${parameter:=word}
foo=
echo ${foo:="default value if unset"}
echo $foo
foo=bar
echo ${foo:="default value if unset"}
echo $foo
Note: Positional and other special parameters cannot be assigned this way.
-
Exit with an error message if the parameter is unset or empty:
${parameter:?word}
foo=
echo ${foo:?"parameter is empty"}
echo $?
foo=bar
echo ${foo:?"parameter is empty"}
echo $?
-
Return the given value only if the parameter is not empty:
${parameter:+word}
foo=
echo ${foo:+"substitute value if set"}
foo=bar
echo ${foo:+"substitute value if set"}
-
Return the names of variables that begin with a prefix:
${!prefix*}
or${!prefix@}
echo ${!BASH*}
echo ${!BASH@}
Download lesson13/part2.cast
Loading asciinema cast...