Cygwin bash 语法错误 - 但脚本在 Ubuntu 中运行良好
#!/bin/bash
if test "$#" == "4"; then echo "$*"; else echo "args-error" >&2; fi;
当我尝试在 Ubuntu 和 Cygwin 上运行这个小代码片段时,它给我带来了很多麻烦。
Ubuntu 运行 bash 版本 4.0+,而 Cygwin 运行 3.2.49;但我认为版本冲突不是造成这种情况的原因,这段代码在 fedora 10 下运行良好,它也使用 bash 版本 3.+
所以基本上我想知道是否有一种方法可以一劳永逸地编写我的脚本,所以有以后就不会再遇到这个可怕的问题了。
非常感谢。
编辑:我目前手头没有 Cygwin,但从我的记忆来看,它一直在说类似无法解析未定义的令牌“fi”之类的内容。
编辑:嗯,原始形式是这样的,刚刚从服务器找到:
#!/bin/bash
if ["$#" == "4"];
then echo "$*";
else echo "args-error" >&2;
fi;
控制台抱怨:
$ ./test.sh 1 2 3
./test.sh: line 2: [3: command not found
args-error
我也想知道为什么 stderr 说出了问题 - 命令未找到 - 但仍然可以打印出答案?
#!/bin/bash
if test "$#" == "4"; then echo "$*"; else echo "args-error" >&2; fi;
This little code snippet troubles me a lot when I tried to run it on both Ubuntu and Cygwin.
Ubuntu runs bash version 4.0+ whereas Cygwin runs 3.2.49; But I reckon version collision shall not be the cause of this, this code runs well under fedora 10 which is also using bash version 3.+
So basically I am wondering if there is a way to code my script once and for all so there are not to have this awful issue later on.
Many thanks in advance.
Edited : I don't have Cygwin by hand at the moment but from my memory, it keeps saying something like couldn't resolve undefined token "fi" something like that.
Edited : well,the original form is like this, just found from server :
#!/bin/bash
if ["$#" == "4"];
then echo "$*";
else echo "args-error" >&2;
fi;
Console complains :
$ ./test.sh 1 2 3
./test.sh: line 2: [3: command not found
args-error
I am also wondering how come that stderr says something goes wrong - command not found - but can still print out the answer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
[
和]
周围需要空格。You need whitespace around the
[
and]
.更新的答案:
您需要在
[
之后有一个空格,否则["$#"
被评估为例如不存在的[3
。试试这个:它对我有用。我猜您会收到这样的错误:
发生这种情况是因为您使用 Windows 样式的行结尾编辑了文件,但 Bash 需要 Unix 样式的行结尾。要修复该文件,请尝试运行以下命令:
您当然需要将文件名更改为脚本的实际文件名。
Updated answer:
You need a space after
[
otherwise["$#"
is evaluated to for example[3
which doesn't exist. Try this:It works for me. I would guess that you are getting an error like this:
This can happen because you have edited the file using Windows-style line endings but Bash expects Unix-style line endings. To fix the file, try running this command:
You of course need to change the filename to the actual filename of your script.
在您显示“原始形式”的编辑中,问题似乎是您在
[
和"
之间缺少空格In your edit to show the 'original form' the problem would seem to be that you're missing a space between the
[
and the"
尝试使用运算符 '=' 而不是 '==' 。并且在
[
之后添加一个空格,在]
之前添加另一个空格,如下所示或者甚至尝试使用“-eq”而不是“==”
因为在某些系统中,它不接受运算符'=='
try to use operator '=' instead of '==' . And also add one space after
[
and another before]
as folowingOr even try '-eq' instead of '=='
Because in some systems, it does not accept the operator '=='