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 $foofoo=barecho ${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 $foofoo=barecho ${foo:="default value if unset"}echo $fooNote: 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=barecho ${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=barecho ${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...