When trying to check if a variable is set or unset in bash, I found the bash conditional expression: -v
(here: True if the shell variable is set (has been assigned a value).). I try the code:
#!/bin/bash
VAR="not-empty"
if [ ! -v "$VAR" ]; then
echo "unset"
else
echo "set: $VAR"
fi
But, the output is unset
even i assigned VAR
at the begin of code.
I found How to check if a variable is set in Bash? question, and tried to replace ! -v
by -z
to check the string variable VAR
. The output is set: non-empty
.
Anyone can help to explain the first case (using -v
expression) why the output is unset
?
My bash version:
GNU bash, version 5.0.17(1)-release (x86_64-pc-linux-gnu) Copyright (C) 2019 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later http://gnu.org/licenses/gpl.html