Bash Syntax Error Near Unexpected Token Fix
In this tutorial, you'll learn about Bash Syntax Error Near Unexpected Token Fix. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
Bash raises syntax error near unexpected token when the script contains unclosed quotes, missing semicolons, misplaced parentheses, or Windows carriage return characters.
The Wrong Way
for i in 1 2 3
do
echo $i
done
Output:
bash: syntax error near unexpected token `done'
The do keyword needs to be on the same line as for or preceded by a semicolon.
The Right Way
for i in 1 2 3; do
echo $i
done
Place do on the same line as for separated by a semicolon.
Step-by-Step Fix
1. Check for Windows line endings
cat -v script.sh | head -5
# If you see ^M$, fix with:
sed -i 's/\r$//' script.sh
2. Fix unclosed quotes
# Wrong
echo "Hello world
# Right
echo "Hello world"
3. Add missing semicolons
# Wrong
for i in 1 2 3; do echo $i done
# Right
for i in 1 2 3; do echo $i; done
4. Check bracket and parenthesis balance
# Wrong
if [ $x -eq 1
then
echo "yes]
fi
# Right
if [ $x -eq 1 ]; then
echo "yes"
fi
5. Use shellcheck to find syntax errors
shellcheck script.sh
Prevention Tips
- Write scripts in a proper code editor with syntax highlighting.
- Use
bash -n script.shto check syntax without executing. - Use
shellcheckto catch common syntax errors automatically. - Avoid Windows editors that add carriage return characters.
- Keep
doandthenon the same line as the control structure.
Common Mistakes with syntax error
- Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists
These mistakes appear frequently in real-world BASH code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro