1

Yes there is a similar thread here: Test if a variable is set in bash when using "set -o nounset"

However there are so many different answers that it's not particularly clear.

Would the following be sufficient to test if a variable is set AND not empty?

#!/bin/bash 
set -o nounset

if [[ ! -z "${EXAMPLE-}" ]]; then
    echo "Variable is defined and is not empty..."
fi
Chris Stryczynski
  • 25,295
  • 38
  • 135
  • 245

2 Answers2

5

Yes, [[ ! -z "${EXAMPLE-}" ]] safely determines whether the variable named EXAMPLE has a non-empty value assigned, even with set -u active.

Personally, I would write [[ -n "${EXAMPLE-}" ]] or even [[ ${EXAMPLE-} ]] -- taking advantage of additional terseness made safe by [[ ]] and not trustworthy with [ ] -- but all these are correct.

Charles Duffy
  • 257,635
  • 38
  • 339
  • 400
2

You can use the -v operator to check if a name has been set to a value:

if [[ -v EXAMPLE ]]; then
    echo "Safe to expand: $EXAMPLE"
fi
chepner
  • 446,329
  • 63
  • 468
  • 610