简体   繁体   English

做的时候Cygwin错误...然后... fi - Bash脚本

[英]Cygwin error when doing if…then…fi - Bash script

I just started bash shell programming. 我刚开始使用bash shell编程。 I have installed Cygwin on my Windows 7 computer. 我在Windows 7计算机上安装了Cygwin。 I started writing a script using this tutorial . 我开始使用本教程编写脚本。 My script requires an argument to be passed to it, if it doesn't it should display an error message. 我的脚本需要传递一个参数,如果没有,它应该显示错误信息。 This is the code directly from the tutorial and the same one in my code: 这是直接来自教程的代码和我的代码中的相同代码:

[ $# -eq 0 ] && { echo "usage: someArgument";  exit 1; }

When I do the following: 当我执行以下操作时:

sh ./myscript.sh

it gives me this error: 它给了我这个错误:

-bash: /home/Me/myscript.sh: line 5: syntax error: unexpected end of file

"Unexpected end of file" means I have missed a fi or done , etc. somewhere. “意外的文件结尾”是指我错过了一个fidone等地方。

I double-checked my code, but found nothing . 我仔细检查了我的代码,但一无所获 Plus, when I comment out the line the script works perfectly fine. 另外,当我注释掉这一行时,脚本的效果非常好。

I tried using a if...then...fi : 我尝试使用if...then...fi

if [ $# -eq 0 ]
then
    echo "usage: someArgument"
    exit 1;
fi

but to no avail! 但无济于事!

Please help, it's been stumping me. 请帮忙,这一直困扰着我。

Probably you have \\r or some other invisible symbols in the script. 可能你在脚本中有\\r或其他一些不可见的符号。 Please add set -x to the beginning of the script to switch debug on and run script once again. 请将set -x添加到脚本的开头以打开调试并再次运行脚本。

Sorry for the trouble. 抱歉,添麻烦了。 I did some research on the invisible symbols mentioned by Igor. 我对伊戈尔提到的隐形符号进行了一些研究。 You have to run dos2unix in Cygwin which solved it for me. 你必须在Cygwin中运行dos2unix ,它为我解决了它。 Dos-type files have \\r\\n instead of \\n and some other stuff which makes Cygwin confused. Dos类型的文件有\\r\\n而不是\\n和其他一些让Cygwin感到困惑的东西。

This: 这个:

$ dos2unix ./myscript.sh
$ sh ./myscript.sh

works correctly. 工作正常。

As an alternative, you can use bash parameter expansion to test for an unset variable. 或者,您可以使用bash参数扩展来测试未设置的变量。 With no positional parameters, $1 will be unset: 没有位置参数,将取消设置$1

: ${1?"usage: someArgument"}

The : command is a null-op, serving as a hook to expand its argument, which is $1 . : command是一个null-op,用作扩展其参数的钩子,即$1 If $1 is unset, the word following the ? 如果未设置$1 ,则后面的单词是? will undergo some expansion and be printed to standard error, after which a non-interactive shell will exit. 将进行一些扩展并打印到标准错误,之后将退出非交互式shell。

(This isn't a solution to your DOS line-ending problem, but just another approach to enforcing that a variable is set.) (这不是解决DOS行结束问题的方法,而只是另一种强制设置变量的方法。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM