检查字符串既不是空的不是shell脚本空间 [英] Check if string is neither empty not space in shell script

查看:198
本文介绍了检查字符串既不是空的不是shell脚本空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行这应该检查是否一个字符串既不是空格,也不空下面的shell脚本。不过,我得到了所有的3串提到相同的输出。我已经使用[[语法尝试很好,但无济于事。

下面是我的code:

 海峡=Hello World的
STR2赛车=
STR3 =如果[! -z$海峡-a$ STR=]!;然后
        echo字符串不为空或空间
科幻如果[! -z$ str2的-a$ str2的=]!;然后
        回声STR2赛车不为空或空间
科幻如果[! -z$ STR3-a$ STR3=]!;然后
        回声STR3不为空或空间
科幻

我收到以下输出:

 #./checkCond.sh
STR不为空或空格
STR2赛车不为空或空格


解决方案

您需要在两侧的空间!= 。更改code为:

 海峡=Hello World的
STR2赛车=
STR3 =如果[! -z$海峡-a$ STR=]!;然后
        echo字符串不为空或空间
科幻如果[! -z$ str2的-a$ str2的=]!;然后
        回声STR2赛车不为空或空间
科幻如果[! -z$ STR3-a$ STR3=]!;然后
        回声STR3不为空或空间
科幻

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.

Here is my code:

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

I am getting the following output:

# ./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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆