Skip to main content

2. Variable expansions

  1. 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"
  2. 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
  3. 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.

  4. 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 $?
  5. 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"}
  6. Return the names of variables that begin with a prefix:
    ${!prefix*} or ${!prefix@}

    echo ${!BASH*}
    echo ${!BASH@}
Loading asciinema cast...