如何使用raspbian的shell命令比较字符串

问题描述 投票:0回答:2

我发现普通linux版本的相关说明不适合RaspberryPi上的raspbian。

例如,以下命令将不起作用,

$s1='bigger'
$s2='smaller'

if (($s1==$s2)); then
  echo equal
else
  echo unequal
fi

有经验的程序员有什么想法吗?谢谢!

linux string shell raspbian
2个回答
1
投票

在 Debian 上这对我来说也不起作用。我会回答假设您使用

#!/bin/bash
(或类似的结构)作为您的 shebang

我收到以下错误:

./b: line 2: =bigger: command not found
./b: line 3: =smaller: command not found
./b: line 5: ((: ==: syntax error: 
operand expected (error token is "==")

一般来说,

$
不应该用在作业的左侧。让我们摆脱那些吧。

s1='bigger'
s2='smaller'

这确实可以运行,但不是我们想要的。

运行修改后的脚本将输出

equal
。这是因为您的双括号
((x == y))
正在执行 算术相等 运算,这不是您想要的。

要检查 bash 中的字符串是否相等,请执行以下操作:

if [[ $s1 == "$s2" ]]; then

这里我引用了条件的右侧以防止全局匹配

[[
构造与
[
不同,功能更强大,但便携性稍差。

最终脚本如下所示:

#!/bin/bash
s1='bigger'
s2='smaller'

if [[ $s1 == "$s2" ]]; then
  echo equal
else
  echo unequal
fi

这符合我们的预期。


0
投票

我回答这个问题(在我刚刚注册之后!)因为我正在尝试这样做,这是我发现的第一个问题/答案。我尝试了费米悖论的答案,但这没有用。我得到了

final.sh:5:[[:未找到

摆脱 [[ 并替换为 [ 给了我

final.sh:5:[:更大:意外的运算符

再次搜索,我找到了另一个答案,导致我

#!/bin/bash
s1='bigger fish'
s2='smaller fish'

if [ "$s1" = "$s2" ]; then
  echo equal
else
  echo unequal
fi
© www.soinside.com 2019 - 2024. All rights reserved.