2

When using the ${parameter:-word} form of parameter expansion to evaluate to a default value if the variable is unset, what is the best practice for quotes?

For example, assume a Bash shell script with -u set (to generate an error when an undefined or unset variable is evaluated), to test if a variable has a value, what would be the best way to write the equivalent of if [[ -z "$FOO" ]]?

if [[ -z "${FOO:-}" ]]

or

if [[ -z ${FOO:-""} ]]

or something else?

jetset
  • 388
  • 4
  • 14

2 Answers2

6

If you are using the latest version of bash (4.2 as of this writing), you can use the -v option to test if a variable is set without trying to expand it at all.

if [[ -v FOO ]]; then
    echo "FOO=$FOO"
else
    echo "FOO not set"
fi

If you are using an older version, I would just use

if [[ -z ${FOO:-} ]];

The quotes aren't necessary, and IMO this looks cleanest.

chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    +1; specifically, the `-v` operator was introduced in `4.2` - see http://tiswww.case.edu/php/chet/bash/NEWS. Older versions: `-z ${FOO:-}` is the _most robust form_ that works in _all_ situations; however, if bash was NOT started with `-u` or `set -u` (`set -o nounset`) was executed, `[[ -z $FOO ]]` works, too. – mklement0 May 01 '14 at 01:43
  • 1
    You don't need the `:` either. – rici May 01 '14 at 03:21
0

I like to do it like this

if (( ! ${#FOO} ))

Example

Zombo
  • 1
  • 62
  • 391
  • 407