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
  • 30,145
  • 48
  • 175
  • 286

2 Answers2

6

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
  • 280,126
  • 43
  • 390
  • 441
4

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
  • 497,756
  • 71
  • 530
  • 681