How to check in Bash (5.x) if a variable is declared, after set for a failing command.
E.g.:
That should output No fail, because FAIL is not declared:
echo "Test" || declare -r FAIL
if [ -v FAIL ]; then echo "Fail"; else echo "No fail"; fi;
That should output Fail, because FAIL is declared:
some_command_not_existing || declare -r FAIL
if [ -v FAIL ]; then echo "Fail"; else echo "No fail"; fi;
However this is not working as expected. I also tried with -z but this is also not working.
I could just make FAIL=true, but I wanted to avoid an unnecessary string.
declarecan tell you if a variable is declared.First, looking at set and
-vThis much we know.
Now, how about declared but unset variables?
And, to remove the output from
declareIf you want a variable set with a non-empty variable to be OK, and any other case to be not OK, you can use
-nNote the the double bracket conditional is more forgiving about unquoted variables. For single bracket conditional, quote it.
Referencing an unset variable clashes with
set -u. For this you can use parameter expansion.