Linux 在 bash 脚本中,if 语句中出现意外的“语法错误:文件意外结束”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7237118/
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
in bash script unexpected "syntax error: unexpected end of file" on if statement
提问by bicepjai
W/hen i run the following code snippet
当我运行以下代码片段时
#!/bin/bash
if [ "foo" = "foo" ];
then
echo "true"
else
echo "false"
fi
echo "end"
i get
我明白了
sfm_write_buffer_test.sh: line 9: syntax error: unexpected end of file
this doesn't make any sense. echo statements works fine, but when the if statement is encountered it gives the above mentioned error.
这没有任何意义。echo 语句工作正常,但是当遇到 if 语句时,它会给出上述错误。
采纳答案by Keith Thompson
You're on Cygwin, right?
你在 Cygwin 上,对吧?
As I said in a comment, when I copy-and-paste your script and run it on my system, it works; the output is
正如我在评论中所说,当我复制并粘贴您的脚本并在我的系统上运行它时,它可以工作;输出是
true
end
But when I change the line endings from the Unix style '\n'
to the Windows style '\r\n'
, I get the same error you got.
但是,当我将行结尾从 Unix 样式'\n'
更改为 Windows 样式时'\r\n'
,我得到了与您相同的错误。
With the Windows-style line endings, bash doesn't see the then
keyword; it sees a command named then\r
. It never tries to execute it because it's scanning for the matching then
or fi
for the if
keyword (which it recognized because it's not at the end of the line).
对于 Windows 风格的行尾,bash 看不到then
关键字;它看到一个名为then\r
. 它从不试图,因为它是扫描用于匹配来执行它then
或者fi
用于if
关键字(其中确认,因为它不是在该行的末端)。
Make sure your shell scripts use Unix-style line endings.
确保您的 shell 脚本使用 Unix 风格的行尾。
回答by densom
The problem is the CRLF at the end of the script. Shell scripts throw this error when they see Windows-style line endings. You need to replace line endings in your shell script with Unix-style LF. Each IDE has it's own way of doing this.
问题是脚本末尾的 CRLF。Shell 脚本在看到 Windows 样式的行结尾时会抛出此错误。你需要用 Unix 风格的 LF 替换你的 shell 脚本中的行尾。每个 IDE 都有自己的方法来做到这一点。
Sublime Text 2==> View -> Line Endings -> Unix
Notepad++==> Edit -> EOL Conversion -> UNIX/OSX Format
Sublime Text 2==> View -> Line Endings -> Unix
Notepad++==> 编辑 -> EOL 转换 -> UNIX/OSX 格式
Once you make that change and save the file, the shell script should execute without error.
进行更改并保存文件后,shell 脚本应该会正确执行。
回答by Noumenon
This wasn't your specific problem, but this can also happen if you have pasted an indented heredoc inside your if statement and it has been converted from tabs to spaces. The end delimiter of the heredoc is never found because of the whitespace, and unexpected end of file is the result.
这不是您的具体问题,但是如果您在 if 语句中粘贴了缩进的 heredoc 并且它已从制表符转换为空格,也会发生这种情况。由于空白,从未找到heredoc的结束分隔符,结果是意外的文件结束。