bash syntax error: unexpected end of file — how to fix
Quick Answer
# Check line endings (CRLF is the usual culprit)
file script.sh
# If: "CRLF line terminators"
dos2unix script.sh
# or
sed -i 's/
//' script.sh
# Check for unclosed blocks — count openers vs closers
grep -c '\bif\b' script.sh # should match fi count
grep -c '\bfi\b' script.sh
When this happens
script.sh: line 42: syntax error: unexpected end of file
# or
script.sh: line 1: syntax error: unexpected end of file
Bash reached the end of the script without finding a closing keyword for an open block (fi, done, esac, }, or ").
Other causes & fixes
Missing fi — if without fi
# WRONG
if [ "$var" = "yes" ]; then
echo "yes"
# Missing: fi
# CORRECT
if [ "$var" = "yes" ]; then
echo "yes"
fi
Missing done — for/while without done
# WRONG
for file in *.txt; do
echo "$file"
# Missing: done
# CORRECT
for file in *.txt; do
echo "$file"
done
Unclosed string or heredoc
# WRONG — unclosed double quote
echo "Hello world
# CORRECT
echo "Hello world"
# Check heredoc delimiter matches exactly
cat <<EOF
content here
EOF
Use bash -n to syntax-check without running
bash -n script.sh
# Prints errors without executing anything
Related