意外标记附近的语法错误 - bash
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8020487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Syntax error near unexpected token - bash
提问by Sriram
I am trying to write a simple bashscript. It just puts out a few lines based on some conditions being satisfied. I am getting stuck on an if-elsecondition and cannot seem to figure a way out.
我正在尝试编写一个简单的bash脚本。它只是根据满足某些条件而放出几行。我陷入困境,if-else似乎无法找到出路。
Here is the code:
这是代码:
if [ ( "${MODE}" == "top10gainers" ) || ( "${MODE}" == "top10losers" ) ]; then
echo "Top Gainers"
elif [ "${MODE}" == "solo" ]; then
echo "Going solo"
fi
The error I get is:
我得到的错误是:
syntax error near unexpected token `"${MODE}"'
`if [ ( "${MODE}" == "top10gainers" ) || ( "${MODE}" == "top10losers" ) ]; then'
I have googled and tried to search forums (including SO) but have not come across a solution. I have also tried out different brackets in the ORcondition, but they have not worked either.
我用谷歌搜索并尝试搜索论坛(包括 SO),但没有找到解决方案。我也在条件中尝试了不同的括号OR,但它们也没有奏效。
回答by Fred Foo
[ "${MODE}" == "top10gainers" ] || [ "${MODE}" == "top10losers" ]
or
或者
[ "${MODE}" == "top10gainers" -o "${MODE}" == "top10losers" ]
回答by Kevin
Parentheses execute their contents in a subshell, that's not what you want, and strings are compared with a single =.
括号在子shell 中执行它们的内容,这不是您想要的,并且字符串与单个=.
if [ "${MODE}" = "top10gainers" ] || [ "${MODE}" = "top10losers" ]; then
echo "Top Gainers"
elif [ "${MODE}" = "solo" ]; then
echo "Going solo"
fi
Note that if you want to compare numbers in the future, use -eqinstead of =.
请注意,如果您以后想比较数字,请使用-eq代替=。
Edit: Testing, I found ==works too, but there's no mention of them in the man page; it might be an extension in the bash built-in version. I'd stick to =if you want to be at all portable.
编辑:测试,我也找到了==作品,但手册页中没有提到它们;它可能是 bash 内置版本的扩展。=如果你想要便携,我会坚持。
回答by Jonathan Callen
Another option, if you are explicitly using bash (that is, starting with #!/bin/bashinstead of #!/bin/sh) is to use bash's builtin [[command, like so:
另一种选择是,如果您明确使用 bash(即以#!/bin/bash代替开头#!/bin/sh),则使用 bash 的内置[[命令,如下所示:
if [[ ${MODE} == top10gainers || ${MODE} == top10loser ]]; then
echo "Top Gainers"
elif [[ ${MODE} == solo ]]; then
echo "Going solo"
fi
Note that [[doesn't require quoting around variables that may contain spaces, unlike [or test.
请注意[[,与[或不同,不需要引用可能包含空格的变量test。

