bash 脚本基本字符串比较
我有一个基本的 bash 脚本问题。我预计该脚本的输出是
: y 乙 x c y
但相反,我得到
: x 乙 x c x
#!/bin/bash
for foo in 'a' 'b' 'c'; do
echo $foo;
if [ "$foo"=="b" ]; then
echo x;
else
echo y;
fi
done;
我错过了什么?
I have a basic bash scripting question. The output of this script, I expected to be:
a
y
b
x
c
y
but instead, I get:
a
x
b
x
c
x
#!/bin/bash
for foo in 'a' 'b' 'c'; do
echo $foo;
if [ "$foo"=="b" ]; then
echo x;
else
echo y;
fi
done;
What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个脚本:
在 bash 中使用
=
进行字符串比较。另外,引用您的echo
字符串。Try this script:
You use
=
for string comparisons in bash. Also, quote yourecho
'd strings.您需要在
==
运算符周围添加空格,否则它将被解析为单个标记a==b
(扩展后,用于第一次迭代)。这将被传递给test
内置函数(其中[
是一个替代名称)。由于单个参数a==b
是一个非空字符串原子,因此它成功并以状态 0 退出,并且then
分支被执行。You need to add spaces around the
==
operator, otherwise it gets parsed as the single tokena==b
(after expansion, for the first iteration). This gets passed to thetest
builtin (for which[
is an alternative name). Since the single argumenta==b
is a non-empty string atom, it succeeds and exits with a status of 0, and thethen
branch gets executed.看看以下内容:
问候,
Rohan Dsouza
Take a look at the following:
Regards,
Rohan Dsouza