How to find whether or not a variable is empty in Bash script

如何检查变量在bash中是否为空?


In bash at least the following command tests if $var is empty :

if [[ -z "$var" ]]; then
   #do what you want
fi

The command man test is your friend.


假设bash:

var=""

if [ -n "$var" ]; then
    echo "not empty"
else
    echo "empty"
fi

I have also seen

if [ "x$variable" = "x" ]; then ...

which is obviously very robust and shell independent.

Also, there is a difference between "empty" and "unset". See How to tell if a string is not defined in a bash shell script?.

链接地址: http://www.djcxy.com/p/97036.html

上一篇: 在Bash脚本中引发错误

下一篇: 如何在Bash脚本中查找变量是否为空