Skip to content

/errors/bash/syntax-error-unexpected-end-of-file

bash: syntax error: unexpected end of file

verified onenvironmentlocal · linux 6.18.44-fc-v140 x64 · GNU bash 5.2.21updated
tool
Bash
exit code
2
versions
Bash 4.x, Bash 5.x
os
linux, macos

syntax error: unexpected end of file means Bash read the whole script and was still inside an open construct: an if without fi, a loop without done, a case without esac, a function with an unclosed {, or a heredoc whose terminator never appeared. The line number in the message is the last line of the file, not the line that is wrong. Find the opener that has no closer.

Reproduce it

bash
cat > app.sh <<'EOF'
if true; then
  echo "hello"
EOF
bash app.sh

Output · exit 2

app.sh: line 3: syntax error: unexpected end of file

The if has no fi. Bash reports the error at the end of the file.

Fix a missing closer

bash
cat > fixed.sh <<'EOF'
if true; then
  echo "hello"
fi
EOF
bash -n fixed.sh && echo "syntax ok"
bash fixed.sh

Output

syntax ok
hello

bash -n parses the script without running it, so it finds this error safely.

OpenerCloser
iffi
for, while, until, selectdone
caseesac
{ (function body or group)}
( (subshell))
<<EOF (heredoc)EOF alone on a line

Heredoc terminator

The terminator must match the delimiter exactly and sit alone on its line. A leading space, a trailing space or a different case leaves the heredoc open until the end of the file. With <<-, leading tabs (not spaces) are allowed.

Windows line endings

A script saved with CRLF endings makes Bash read fi as fi followed by a carriage return, which is not the keyword. Convert the file:

bash
sed -i 's/\r$//' script.sh    # GNU sed; on macOS use sed -i '' 's/\r$//' script.sh

Sources