/errors/bash/syntax-error-unexpected-end-of-file
bash: syntax error: unexpected end of file
- 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
cat > app.sh <<'EOF'
if true; then
echo "hello"
EOF
bash app.shOutput · 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
cat > fixed.sh <<'EOF'
if true; then
echo "hello"
fi
EOF
bash -n fixed.sh && echo "syntax ok"
bash fixed.shOutput
syntax ok hello
bash -n parses the script without running it, so it finds this error safely.
| Opener | Closer |
|---|---|
| if | fi |
| for, while, until, select | done |
| case | esac |
| { (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:
sed -i 's/\r$//' script.sh # GNU sed; on macOS use sed -i '' 's/\r$//' script.sh