使用 sh shell 比较字符串 [英] Compare a string using sh shell

查看:47
本文介绍了使用 sh shell 比较字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SH shell 并且我试图将一个字符串与一个变量的值进行比较,但是 if 条件总是执行为真.为什么?

I am using SH shell and I am trying to compare a string with a variable's value but the if condition is always execute to true. Why?

这是一些代码:

Sourcesystem="ABC"

if [ "$Sourcesystem" -eq 'XYZ' ]; then 
    echo "Sourcesystem Matched" 
else
    echo "Sourcesystem is NOT Matched $Sourcesystem"  
fi;

echo Sourcesystem Value is  $Sourcesystem ;

即使这样也行不通:

Sourcesystem="ABC"

if [ 'XYZ' -eq "$Sourcesystem" ]; then 
    echo "Sourcesystem Matched" 
else
    echo "Sourcesystem is NOT Matched $Sourcesystem"  
fi;

echo Sourcesystem Value is  $Sourcesystem ;

其次,我们可以将其与 NULL 或空字符串匹配吗?

Secondly, can we match this with a NULL or empty string?

推荐答案

您应该使用 = 运算符进行字符串比较:

You should use the = operator for string comparison:

Sourcesystem="ABC"

if [ "$Sourcesystem" = "XYZ" ]; then 
    echo "Sourcesystem Matched" 
else
    echo "Sourcesystem is NOT Matched $Sourcesystem"  
fi;

man test 表示您使用 -z 来匹配空字符串.

man test says that you use -z to match for empty strings.

这篇关于使用 sh shell 比较字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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