Bash function to check if a given variable is set

Viewed 875

As explained in this answer, the "right" way to check if a variable is set in bash looks like this:

if [ -z ${var+x} ]; then
    echo "var is unset"
else
    echo "var is set to '$var'"
fi

What I'm interested in is how to extract this into a function that can be reused for different variables.

The best I've been able to do so far is:

is_set() {
  local test_start='[ ! -z ${'
  local test_end='+x} ]'
  local tester=$test_start$1$test_end

  eval $tester
}

It seems to work, but is there a better way that doesn't resort to calling eval?

2 Answers
Related