天天看点

linux shell 中判断字符串为空的正确方法

help命令可以查看帮助

help test

正确做法:

#!/bin/sh

STRING=

if [ -z "$STRING" ]; then

    echo "STRING is empty"

fi

if [ -n "$STRING" ]; then

    echo "STRING is not empty"

fi

[email protected]:~# ./zerostring.sh

STRING is empty

-------------------------------------------------------------------------

错误做法:

#!/bin/sh

STRING=

if [ -z $STRING ]; then

    echo "STRING is empty"

fi

if [ -n $STRING ]; then

    echo "STRING is not empty"

fi 

输出错误结果:

[email protected]:~# ./zerostring.sh

STRING is empty

STRING is not empty

继续阅读