What is this bash parameter expansion syntax?

134 Views Asked by At

I've never seen this +x} syntax before and I can't find docs about it. What does it do?

if [[ -z "${EMPLOYEE_CLUSTER+x}" ]]; then
  export EMPLOYEE_CLUSTER=shared
fi
1

There are 1 best solutions below

0
On BEST ANSWER

If the variable EMPLOYEE_CLUSTER is defined (even to an empty string), the expansion expands to x. Since x is not an empty string, the [[ test will evaluate to true. If the variable is not defined, the expansion expands to nothing, and the test evaluates to false. Note that the presence of a colon in ${EMPLOYEE_CLUSTER:+x} changes the expansion; the variable must be set and non-empty to get the x output.

It is a slightly unusual usage, but it is hard to do better in a test like that where an empty value is permissible but the variable must be set. The notation is more commonly used to conditionally pass values to a command. For example:

mythical-creature ${UNICORN:+"-u"} ${UNICORN}

This will pass the -u option to mythical-creature if $UNICORN is defined and non-empty — as well as the value stored in $UNICORN. If $UNICORN is not defined and non-empty, no arguments are passed to the command.

See Shell parameter expansion in the Bash manual — it is the fourth documented notation in this section.