/ bin / sh:奇数字符串比较错误'意外操作员'

时间:2014-09-15 10:55:12

标签: shell sh

发现此错误非常奇怪,因为之前我的脚本正在运行,但在我从服务器移动它后,我正在使用本地计算机,它停止工作,只是给了我一个意外的操作员&#39 ;错误。

# Else if the script is being run in the arrayscripts directory, add /output/ ...
elif [ $basePath == "arrayscripts" ];
then
        echo "$dscr has started to run."
        cpuPath="`pwd`/output/cpu.binary"
        txtPath="`pwd`/output/cpu.txt"
        csvPath="`pwd`/output/cpu.csv"

3 个答案:

答案 0 :(得分:10)

如果您的实际shell是/bin/sh [与初始问题相反,但正如讨论评论已明确指出],请在测试表达式中使用=而不是==

elif [ "$basePath" = arrayscripts ]

请注意,在这种情况下,右侧不需要引用,因为它不包含扩展且不包含语法敏感字符。


或者,如果在使用bash时此问题可重现,则明显的问题是缺少引号。

使用

[ "$basePath" = arrayscripts ] # this is POSIX compatible

[[ $basePath = arrayscripts ]] # this works only with bash

否则,$basePath扩展的参数个数是未定义的 - 它可能扩展为零参数,使语句

[ = arrayscripts ]

...会尝试将=用作一元运算符,而不是......

或如果包含$basePath,例如"true -o bar =",它可能会扩展为类似

[ true -o bar = arrayscripts ]

...导致程序行为与您实际想要的完全不同。


底线:当编写遵循POSIX规则的shell(基本上,除了zsh或fish之外的任何东西)时,引用您的扩展,除非您有特定且令人信服的理由不这样做。 (使用bash / ksh扩展名[[ ]]提供了这样一个原因,引入了一个上下文,其中不会发生扩展结果和全局扩展的字符串拆分。)

答案 1 :(得分:2)

如果您使用像dash这样的POSIX shell执行脚本,则会出现此错误。 dash是某些平台上的默认/bin/sh,例如Ubuntu和Debian。

==特定于bashBashism),与dash等POSIX shell不兼容,后者只使用=来测试字符串相等性。

在单括号的上下文中,===bash中被视为同一个运算符,因此可以使用其中任何一个。

答案 2 :(得分:0)

我设法通过更改' =='的比较功能让我的脚本正常工作到' ='正如alister'所建议的那样。在unix和linux论坛(http://www.unix.com/shell-programming-and-scripting/141856-how-avoid-unexpected-operator-error-when-comparing-2-strings.html),所以我的脚本看起来像这样

# Else if the script is being run in the arrayscripts directory, add /output/ ...
    elif [ "$basePath" = "arrayscripts" ];
    then
            echo "$dscr has started to run."
            cpuPath="`pwd`/output/cpu.binary"
            txtPath="`pwd`/output/cpu.txt"
            csvPath="`pwd`/output/cpu.csv"

希望如果有人像我一样得到同样的错误,那么这个答案对他们有帮助。

相关问题