bash 在 ksh 中比较字符串的相等性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1660507/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 18:38:56  来源:igfitidea点击:

Comparing strings for equality in ksh

bashunixshellksh

提问by Vijay

i am testing with the shell script below:

我正在使用下面的 shell 脚本进行测试:

#!/bin/ksh -x


instance=`echo  | cut -d= -f2`
if [ $instance == "ALL" ]
then
echo "strings matched \n"
fi

It's giving this error in the if condition:

它在 if 条件下给出了这个错误:

: ==: unknown test operator

is ==really not the correct syntax to use? I am running on the command line as below

==真的不使用正确的语法?我在命令行上运行如下

test_lsn_2 INSTANCE=ALL

Could anybody please suggest a solution. Thanks.

任何人都可以请提出解决方案。谢谢。

采纳答案by Alberto Zaccagni

I see that you are using ksh, but you added bash as a tag, do you accept a bash-related answer? Using bash you can do it in these ways:

我看到您正在使用 ksh,但是您添加了 bash 作为标签,您是否接受与 bash 相关的答案?使用 bash,您可以通过以下方式进行操作:

if [[ "$instance" == "ALL" ]]
if [ "$instance" = "ALL" ]
if [[ "$instance" -eq "ALL" ]]

See herefor more on that.

有关更多信息,请参见此处

回答by Andre Miller

To compare strings you need a single =, not a double. And you should put it in double quotes in case the string is empty:

要比较字符串,您需要一个 =,而不是双。如果字符串为空,您应该将其放在双引号中:

if [ "$instance" = "ALL" ]
then
    echo "strings matched \n"
fi

回答by Aaron Digulla

Try

尝试

if [ "$instance" = "ALL" ]; then

There were several mistakes:

有几个错误:

  1. You need double quotes around the variable to protect against the (unlikely) case that it's empty. In this case, the shell would see if [ = "ALL" ]; thenwhich isn't valid.

  2. Equals in the shell uses a single =(there is no way to assign a value in an ifin the shell).

  1. 您需要在变量周围加上双引号以防止(不太可能)它为空的情况。在这种情况下,shell 会看到if [ = "ALL" ]; then哪个无效。

  2. Equals 在 shell 中使用单个=(在 shell中无法在 anif中赋值)。

回答by ghostdog74

totest=
case "$totest" in
  "ALL" ) echo "ok" ;;
  * ) echo "not ok" ;;
esac

回答by soulmerge

I'va already answered a similar question. Basically the operator you need is =(not ==) and the syntax breaks if your variable is empty (i.e. it becomes if [ = ALL]). Have a look at the other answerfor details.

我已经回答了一个类似的问题。基本上,您需要的运算符是=(not ==),如果您的变量为空(即变为if [ = ALL]),则语法会中断。详情请查看其他答案