0%

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

正确的做法

1
2
3
4
5
6
7
8
9
10
11
#!/bin/sh

STRING=

if [ -z "$STRING" ]; then
echo "STRING is empty"
fi

if [ -n "$STRING" ]; then
echo "STRING is not empty"
fi

输出正确的结果:

1
2
root@james-desktop:~# ./zerostring.sh
STRING is empty

错误的做法

1
2
3
4
5
6
7
8
9
10
11
#!/bin/sh

STRING=

if [ -z $STRING ]; then
echo "STRING is empty"
fi

if [ -n $STRING ]; then
echo "STRING is not empty"
fi

输出错误结果:

1
2
3
root@james-desktop:~# ./zerostring.sh
STRING is empty
STRING is not empty

总结

记得在给变量加上双引号””

参考链接

https://www.cnblogs.com/cute/archive/2011/08/26/2154137.html