3

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
2
  • 3
    This is covered by BashFAQ #112. Commented Nov 22, 2017 at 14:47
  • 1
    BashFAQ #112 could use an update; it doesn't mention the -v operator. Commented Nov 22, 2017 at 15:01

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

Comments

7

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

1 Comment

Notice that this requires Bash 4.2 or newer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.