我如何检查一个变量是否为空的Bash?
当前回答
假设Bash:
var=""
if [ -n "$var" ]; then
echo "not empty"
else
echo "empty"
fi
其他回答
if [[ "$variable" == "" ]] ...
如果变量未设置或设置为空字符串(""),则返回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
我也看到过
if [ "x$variable" = "x" ]; then ...
这显然是非常健壮和外壳无关的。
此外,“empty”和“unset”之间也有区别。请参阅如何判断字符串是否未在Bash shell脚本中定义。
[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}