/bin/sh: 奇数字符串比较错误“意外的运算符" [英] /bin/sh: Odd string comparison error 'unexpected operator'

查看:36
本文介绍了/bin/sh: 奇数字符串比较错误“意外的运算符"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

发现这个错误很奇怪,因为之前我的脚本可以正常工作,但是在我将它从我正在处理的服务器移到我的本地机器后,它停止工作,只是给了我一个意外的操作员"错误.

Found this error to be quite weird because previously my script was working and but after I moved it from the server I was working on to my local machine, it stopped working and just gave me an 'unexpected operator' error.

# 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"

推荐答案

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

If your actual shell is /bin/sh [contrary to the initial question, but as discussion commentary has made clear], use = rather than == in your test expression:

elif [ "$basePath" = arrayscripts ]

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

Note that the right-hand side doesn't need to be quoted in this case, since it contains no expansions and no syntactically-sensitive characters.

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

Alternately, if this issue is reproducible when using bash, the obvious problem is missing quotes.

使用任一

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

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

否则,$basePath 扩展成的参数数量是不确定的——它可能扩展成零个参数,使语句

Otherwise, the number of arguments $basePath expands into is undefined -- it may expand into zero arguments, making the statement

[ = arrayscripts ]

...它会尝试使用 = 作为一元运算符,它不是...

...which would try to use = as a unary operator, which it isn't...

或者如果 $basePath 包含,比如说,"true -o bar =",它可以扩展成类似

or if $basePath contained, say, "true -o bar =", it could expand into something like

[ true -o bar = arrayscripts ]

...导致程序行为与您实际想要的非常不同.

...resulting in program behavior very different from what you actually want.

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

Bottom line: When writing for shells which follow POSIX rules (basically, anything but zsh or fish), quote your expansions unless you have a specific and compelling reason to do otherwise. (Use of the bash/ksh extension [[ ]] provides such a reason, by introducing a context in which string-splitting of expansion results and glob expansion don't take place).

这篇关于/bin/sh: 奇数字符串比较错误“意外的运算符"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆