在ksh中比较字符串是否相等

Vij*_*jay 6 unix bash shell ksh

我正在测试下面的shell脚本:

#!/bin/ksh -x


instance=`echo $1 | cut -d= -f2`
if [ $instance == "ALL" ]
then
echo "strings matched \n"
fi
Run Code Online (Sandbox Code Playgroud)

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

: ==: unknown test operator
Run Code Online (Sandbox Code Playgroud)

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

test_lsn_2 INSTANCE=ALL
Run Code Online (Sandbox Code Playgroud)

有人可以建议一个解决方案.谢谢.

And*_*ler 16

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

if [ "$instance" = "ALL" ]
then
    echo "strings matched \n"
fi
Run Code Online (Sandbox Code Playgroud)


Alb*_*gni 6

我看到你正在使用ksh,但你添加了bash作为标签,你接受与bash相关的答案吗?使用bash,你可以通过以下方式实现:

if [[ "$instance" == "ALL" ]]
if [ "$instance" = "ALL" ]
if [[ "$instance" -eq "ALL" ]]
Run Code Online (Sandbox Code Playgroud)

有关详情,请参阅此处.

  • 我认为第三种选择并不是一个好主意.AFAIK,-eq用于整数比较,而不是字符串. (2认同)

Aar*_*lla 5

尝试

if [ "$instance" = "ALL" ]; then
Run Code Online (Sandbox Code Playgroud)

有几个错误:

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

  2. shell 中的 equals 使用单个=(shell 中无法在 an 中赋值if)。