开发者

Improve script output

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 d开发者_如何学Pythono it breaks.

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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜