2009-11-02 128 views
6

我与下面的shell脚本测试:比较字符串在KSH平等

#!/bin/ksh -x 


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

它给这个错误的,如果条件:

: ==: unknown test operator 

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

test_lsn_2 INSTANCE=ALL 

有谁请提出一个解决方案。 谢谢。

+1

把双引号括在''instance''的'if'中并再次尝试。让我知道,如果这项工作。 – NawaMan 2009-11-02 10:41:41

+0

不要在'$ instance'放双引号不工作:( – Vijay 2009-11-02 10:45:23

+0

哪个版本的'ksh'是这个? – 2013-03-08 20:26:33

回答

5

我看到你正在使用ksh,但你添加了bash作为标记,你接受bash相关的答案吗? 使用bash,你可以做到这一点在以下方面:

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

要了解他们见here

+0

感谢您的回复monte。as andre miller said == not working = working.i will accept ur answer but也为+1 andre – Vijay 2009-11-02 10:52:55

+0

我认为第三个选项不是一个好主意。AFAIK,-eq用于整数比较,而不是字符串。 – Daniel 2014-12-12 13:32:48

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

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

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

谢谢你的建议 – Vijay 2009-11-02 10:53:24

0

我已经回答了类似的问题。基本上,您需要的运算符是=(而不是==),如果变量为空(即它变为if [ = ALL]),语法将中断。详情请看the other answer

4

尝试

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

有几个错误:

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

  2. shell中的等号使用单个=(shell中的if没有办法指定值)。