Expand a Bash Variable Only When It Is Set and Non-Empty
Expand a word only when a variable is set and non-empty with the plus form of parameter expansion, which suits optional flags. It works in Bash 3.2 and POSIX sh.
You want a command line to carry an extra flag only when some variable is turned on, without an if statement around the whole command.
name=ann; empty=
echo "name: [${name:+set}]"
echo "empty: [${empty:+set}]"
echo "unset: [${nothing:+set}]"
DEBUG=1
flag=${DEBUG:+--verbose}
echo "curl ${flag} -s example.org"
unset DEBUG
flag=${DEBUG:+--verbose}
echo "curl ${flag} -s example.org"name: [set]
empty: []
unset: []
curl --verbose -s example.org
curl -s example.orgThe ${var:+word} form expands to word when var is set and not empty, and to nothing otherwise, so flag=${DEBUG:+--verbose} gives either the flag or an empty string. The run shows all three cases: set, empty and unset. The colon matters, because the form without it, ${var+word}, treats an empty value as set. The rule is in the Shell Parameter Expansion section of the manual and in POSIX, so it also works in dash.
An unquoted empty expansion leaves the spaces around it behind, which is the double space in the second curl line, and quoting it would pass an empty argument instead. For more than one optional flag, collect them in an array and expand it with "${opts[@]}".