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?
Are you seeing if the variable is undefined or simply a null string?
Null Test
Undefined Test
The last is looking at the output of the
setcommand to see if the variable is listed there. The-qwill makegrepquiet. And you look at the exit status to see if it found the string. If yourgrepdoesn’t support the-qparameter, you can trygrep "^$var=" 2> /dev/null.Using the
[[ $foo ]]syntax for testing won’t necessarily work. The below will print$foo is not seteven though it was set to an empty string: