2
BashERRORNotableScriptingHIGH confidence

Syntax error

What this means

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.

Why it happens
  1. 1Missing keywords like `do`, `done`, `fi`, `then`.
  2. 2Mismatched quotes or parentheses.
  3. 3Using operators or commands incorrectly.
How to reproduce

A script has an unclosed `if` statement.

trigger — this will error
trigger — this will error
#!/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

Run the script with `bash -n`
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

Use a linter
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.

What not to do

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.

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Bash errors