我使用shell脚本来比较2个字符串变量是否为空白。并根据哪些变量为空白运行一些动作。
a=""
b=""
read a
read b
if [ -z $a ] && [ -n $b ] ;then
echo "Var a is blank"
elif [ -n $a ] && [ -z $b ] ;then
echo "Var b is blank"
elif [ -n $a ] && [ -n $b ] ; then
echo "Both fields not empty"
else
echo "Both fields are blank"
fi
如果我的字符串varibles有空格,我收到了if else语句的二元运算符预期错误。我究竟做错了什么?请帮忙。
答案 0 :(得分:2)
您有语法错误。你可以用这个:
if [[ -z "$a" && -n "$b" ]]; then
echo "a is empty"
elif [[ -n "$a" && -z "$b" ]]; then
echo "b is empty"
elif [[ -z "$a" && -z "$b" ]]; then
echo "both are empty"
else
echo "both are non-empty"
fi
答案 1 :(得分:1)
始终双引号变量,如下所示:
if [ -z "$a" ] && [ -n "$b" ] ;then
...
这将保护字符串中的任何空格。