In bash script, unexpected "syntax error: unexpected end of file" in if statement

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 

it makes no sense. The echo statements work fine, but when an if statement is encountered, it throws the above error.

+4
source share
3 answers

You're on Cygwin, right?

As I said in the comment, when I copy and paste your script and run it on my system, it works; output

 true end 

But when I change the line ending from Unix style '\n' to Windows style '\r\n' , I get the same error.

At the end of a line in the style of Windows bash, then is not displayed; he sees a command named then\r . It never tries to execute it because it scans the then or fi match for the if keyword (which it recognized because it is not at the end of the line).

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

+8
source

The problem is the CRLF at the end of the script. Shell scripts cause this error when they see Windows-style line endings. You need to replace the line endings in your shell script with a Unix-style LF. Each IDE has its own way of doing this.

Sublime Text 2 ==> Browse β†’ Linear Ends β†’ Unix

Notepad ++ ==> Edit β†’ EOL Conversion β†’ UNIX / OSX Format

After making changes and saving the file, the shell script should run without errors.

+3
source

This is not your specific problem, but it can also happen if you indented heredoc in your if statement and it was converted from tabs to spaces. The final heredoc delimiter was never found due to a space, and the result is an unexpected end to the file.

0
source

Source: https://habr.com/ru/post/1369584/


All Articles