为什么我在 bash 字符串相等性测试中遇到意外的运算符错误?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18102454/
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
Why am i getting an unexpected operator error in bash string equality test?
提问by John Hall
Where is the error on line four?
第四行的错误在哪里?
if [ $bn == README ]; then
which i still get if i write it as
如果我把它写成,我仍然会得到
if [ $bn == README ]
then
or
或者
if [ "$bn" == "README" ]; then
Context:
语境:
for fi in /etc/uwsgi/apps-available/*
do
bn=`basename $fi .ini`
if [ $bn == "README" ]
then
echo "~ ***#*** ~"
else
echo "## Shortend for convience ##"
fi
done
回答by konsolebox
You can't use == for single bracket comparisons ([ ]). Use single = instead. Also you must quote the variables to prevent expansion.
不能将 == 用于单括号比较 ([ ])。使用单个 = 代替。此外,您必须引用变量以防止扩展。
if [ "$bn" = README ]; then
If you use [[ ]], that could apply and you wouldn't need to quote the first argument:
如果您使用 [[ ]],那可能适用并且您不需要引用第一个参数:
if [[ $bn == README ]]; then
回答by Christopher Neylan
Add the following to the top of your script:
将以下内容添加到脚本的顶部:
#! /bin/bash
In bash, ==
is the sameas =
when used inside of single brackets. This is, however, not portable. So you should explicitly tell the shell to use bash as the script's interpreter by putting #! /bin/bash
at the top of the script.
在bash中,==
相同的=
单一支架内使用时。然而,这不是便携式的。因此,您应该通过放置#! /bin/bash
在脚本的顶部来明确告诉 shell 使用 bash 作为脚本的解释器。
Alternatively, do your string comparisons using =
. Note that the ==
operator behaves differentlywhen used inside of double-brackets than when inside of single-brackets (see the link).
或者,使用=
. 请注意,==
运算符在双括号内使用时的行为与在单括号内使用时的行为不同(请参阅链接)。