Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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..."

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.

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"
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.