0

I have written a function which checks whether one or more variables passed as arguments are empty (got the idea from here)

Here is what the script looks like:

#!/bin/bash
is_variable_defined?() {
 for VAR in "$@"; do
  : "${!VAR? "ERROR: $VAR is undefined."}"
 done
}

TEST='a'

is_variable_defined? TEST TEST2

And here is the output:

/path/to/script.sh: line 4: !VAR:  ERROR: TEST2 is undefined.

However what I would like to output is:

TEST2 is undefined

I have tried tweaking the : "${!VAR? "ERROR: $VAR is undefined."}" line but whatever I do it breaks.

Does anybody know what to modify in the script to get the output I want?

Community
  • 1
  • 1
Max
  • 12,794
  • 30
  • 90
  • 142
  • 1
    Did you even read the answer from the question you link to? It's **intended** to break with that message. The answer on the other question holds the answer, as far as I can see it. – Bobby May 23 '11 at 12:16
  • possible duplicate of [Bash. Test for a variable unset, using a function](http://stackoverflow.com/questions/874389/bash-test-for-a-variable-unset-using-a-function) – Bobby May 23 '11 at 12:17
  • hence my question, how can I change the message? – Max May 23 '11 at 12:37
  • 2
    You can't, it's a built in function. May I quote from [lhunath answer](http://stackoverflow.com/questions/874389/bash-test-for-a-variable-unset-using-a-function/874520#874520) from that other question: `If you just want to test whether foo is empty, instead of aborting the script, use this instead of a function: [[ $foo ]]`. – Bobby May 23 '11 at 12:55

1 Answers1

2

Are you seeing if the variable is undefined or simply a null string?

Null Test

is_variable_defined() {
    for var in $@
    do
        if [ -z ${!var} ]   # Or if [[ ${!var} ]]
        then
            echo "Var $var has no value"
        fi
    done
}

Undefined Test

is_variable_defined() {
for var in $@
do
     if ! set | grep -q "^$var="
     then
        echo "Var $var is not set"
     fi
done

The last is looking at the output of the set command to see if the variable is listed there. The -q will make grep quiet. And you look at the exit status to see if it found the string. If your grep doesn't support the -q parameter, you can try grep "^$var=" 2> /dev/null.


Using the [[ $foo ]] syntax for testing won't necessarily work. The below will print $foo is not set even though it was set to an empty string:

foo=""
if [[ $foo ]]
then
      echo "\$foo = '$foo'"
else
      echo "\$foo is not set"
fi
David W.
  • 105,218
  • 39
  • 216
  • 337
  • +1 for introducing the `set` command, although relying on grep to verify a variable status may not be as robust as the `[[ $foo ]]` function suggested by Bobby. – Max May 24 '11 at 07:59
  • The problem is that `[[ $foo ]]` also will fail if `$foo` has a value, but is null. The `set` test can tell the difference between `foo` having a value that's null and `$foo` not being set. – David W. May 24 '11 at 14:36