Check Empty Variable Linux Bash
You can determine if a variable is empty in Linux using the following methods:
- Check if the variable is empty using an if statement.
if [ -z "$var" ]; then
echo "变量 var 为空"
else
echo "变量 var 不为空"
fi
- Check if a variable is empty using the test command.
if test -z "$var"; then
echo "变量 var 为空"
else
echo "变量 var 不为空"
fi
The -z option is used to test if a variable is empty. It returns true if the variable is empty, otherwise it returns false.
Alternatively, you can also use the following simplified method for evaluation:
[ -z "$var" ] && echo "变量 var 为空" || echo "变量 var 不为空"
Alternatively:
test -z "$var" && echo "变量 var 为空" || echo "变量 var 不为空"