检查shell脚本中的字符串是否既不为空也不为空 [英] Check if string is neither empty nor space in shell script
本文介绍了检查shell脚本中的字符串是否既不为空也不为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试运行以下shell脚本,该脚本应检查字符串是否既不是空格也不为空.但是,对于所有上述3个字符串,我都得到相同的输出.我也尝试过使用[[]语法,但无济于事.
I am trying to run the following shell script which is supposed to check if a string is neither space nor empty. However, I am getting the same output for all the 3 mentioned strings. I have tried using the "[[" syntax as well but to no avail.
这是我的代码:
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str"!=" " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2"!=" " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3"!=" " ]; then
echo "Str3 is not null or space"
fi
我得到以下输出:
# ./checkCond.sh
Str is not null or space
Str2 is not null or space
推荐答案
您需要在!=
的两边都留一个空格.将您的代码更改为:
You need a space on either side of the !=
. Change your code to:
str="Hello World"
str2=" "
str3=""
if [ ! -z "$str" -a "$str" != " " ]; then
echo "Str is not null or space"
fi
if [ ! -z "$str2" -a "$str2" != " " ]; then
echo "Str2 is not null or space"
fi
if [ ! -z "$str3" -a "$str3" != " " ]; then
echo "Str3 is not null or space"
fi
这篇关于检查shell脚本中的字符串是否既不为空也不为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文