Skip to content
shellhacks.dev
Bash

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.

1 min read
Summarize in AI

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.

Shell
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"
Text
name:  [set]
empty: []
unset: []
curl --verbose -s example.org
curl  -s example.org

The ${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[@]}".

Share

More snippets

Bash

Reverse a String in Pure Bash Without rev

Reverse a string in pure Bash with a for loop and substring expansion. It handles UTF-8, but it took about 2 seconds for 20000 characters where rev took 2 milliseconds.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.