检查string在shell脚本中是否既不空也不空格

我试图运行下面的shell脚本,应该检查一个string既不是空格也不是空的。 但是,我得到的所有3个string的输出相同。 我曾尝试使用“[[”语法,但无济于事。

这是我的代码:

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 

你需要在!=两边有一个空格。 将您的代码更改为:

 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中的空string

 if [ "$str" == "" ];then echo NULL fi 

要么

 if [ ! "$str" ];then echo NULL fi 

如果你需要检查任何数量的空白,而不是单个空间,你可以这样做:

去除额外的空白string(也可以将中间的空白字符放在一个空格中):

 trimmed=`echo -- $original` 

--确保如果$original包含了被echo所理解的开关,它们仍然被认为是被回显的普通参数。 另外重要的是不要把""放在$original ,否则空格不会被删除。

之后,你可以检查$trimmed是否为空。

 [ -z "$trimmed" ] && echo "empty!" 

要检查一个string是空的还是只包含空格,你可以使用:

 shopt -s extglob # more powerful pattern matching if [ -n "${str##+([[:space:]])}" ]; then echo '$str is not null or space' fi 

请参阅Bash手册中的Shell参数扩展和模式匹配 。

另一个快速testingstring有一些东西,但空间。

 if [[ ! -z "${str/ //}" ]]; then echo "It is not empty!" fi 
 [ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty" 

剥离string中的所有换行符和空格将导致空白的空格被减less为无法testing和执行的任何内容