Syntax error
A syntax error is reported by the shell when it parses a script and finds code that violates its grammatical rules. The script cannot be executed until the syntax is corrected.
- 1Missing keywords like `do`, `done`, `fi`, `then`.
- 2Mismatched quotes or parentheses.
- 3Using operators or commands incorrectly.
A script has an unclosed `if` statement.
#!/bin/bash # Missing 'then' if [ 1 -eq 1 ] echo "equal" fi
expected output
bash: myscript.sh: line 4: syntax error near unexpected token 'fi' bash: myscript.sh: line 4: 'fi'
Fix 1
Run the script with `bash -n`
WHEN Debugging a syntax error
bash -n your_script.sh
Why this works
The `-n` option tells bash to read the script and check for syntax errors without executing it. This is a safe way to validate a script's syntax.
Fix 2
Use a linter
WHEN Developing scripts
shellcheck your_script.sh
Why this works
Tools like ShellCheck are static analysis tools that can find a wide range of syntax errors and common scripting pitfalls.
✕ Add or remove lines randomly until it works
This can hide the real issue or introduce new bugs. It is better to understand the reason for the syntax error.
GNU Bash Manual — Shell Syntax
ShellCheck - A static analysis tool for shell scripts ↗Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev