我如何检查一个变量是否为空的Bash?
当前回答
假设Bash:
var=""
if [ -n "$var" ]; then
echo "not empty"
else
echo "empty"
fi
其他回答
if [[ "$variable" == "" ]] ...
在Bash中,至少下面的命令会测试$var是否为空:
if [[ -z "$var" ]]; then
# $var is empty, do what you want
fi
指挥人测试是你的朋友。
if [ ${foo:+1} ]
then
echo "yes"
fi
如果设置了变量,则打印yes。${foo:+1}在设置变量时将返回1,否则将返回空字符串。
如果变量未设置或设置为空字符串(""),则返回true。
if [ -z "$MyVar" ]
then
echo "The variable MyVar has nothing in it."
elif ! [ -z "$MyVar" ]
then
echo "The variable MyVar has something in it."
fi
假设Bash:
var=""
if [ -n "$var" ]; then
echo "not empty"
else
echo "empty"
fi