in bash script unexpected “syntax error: unexpected end of file” on if statement [duplicate]

半腔热情 提交于 2019-12-23 09:44:41

问题


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.


回答1:


You're on Cygwin, right?

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.

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).

Make sure your shell scripts use Unix-style line endings.




回答2:


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.

Sublime Text 2 ==> View -> Line Endings -> Unix

Notepad++ ==> Edit -> EOL Conversion -> UNIX/OSX Format

Once you make that change and save the file, the shell script should execute without error.




回答3:


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.



来源:https://stackoverflow.com/questions/7237118/in-bash-script-unexpected-syntax-error-unexpected-end-of-file-on-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!