Public

How to Fix "syntax error near unexpected token" in Bash

This article contains ads and affiliate links.

Linux/Bash/Shell Linux
t-salad t-salad committed 94c82ab

When you run a Bash script, you may hit an error like this:

Sponsored Links
script.sh: line 10: syntax error near unexpected token `('

This means Bash reached a token (a symbol or word) it did not expect while parsing your script. The token printed after near unexpected token is the clue to where the real problem is. Below are the most common causes, ordered by how often they actually happen, plus how to pinpoint the line.

Common causes

1. Windows-style (CRLF) line endings

This is one of the most common and confusing causes. If the script was edited on Windows, each line ends with a carriage return, and Bash reports a token like $'\r':

script.sh: line 5: syntax error near unexpected token `$'\r''

Convert the file to Unix line endings:

sed -i 's/\r$//' script.sh
# or
dos2unix script.sh

2. Unmatched quotes, parentheses, or braces

A missing closing ", ), or } makes Bash keep reading past where you expected the statement to end, so the error often points to a line after the real mistake. Check that every opening symbol has a matching closing one.

3. Missing spaces around [ ] and operators

Bash needs spaces around the test brackets. This fails:

if [ "$a" -eq 1 ]; then   # correct
if ["$a" -eq 1]; then     # error: no spaces inside [ ]

4. Missing then / fi / do / done or a missing semicolon

An unterminated if or for block triggers the error at the next unexpected token:

if [ "$a" -eq 1 ]; then
    echo "a is 1"
fi   # do not forget fi

5. Running a Bash script with sh

If the script uses Bash-only syntax but is run as sh script.sh (where /bin/sh is dash), constructs like arrays or [[ ... ]] raise this error. Run it with bash script.sh or set the shebang to #!/usr/bin/env bash.

Sponsored Links

How to locate the error

  • Read the message: it prints the line number and the unexpected token. Start there and look a line or two above.
  • Check syntax without running: bash -n script.sh parses the script and reports syntax errors only.
  • Trace execution: add set -x near the top to print each command as it runs.
  • Use ShellCheck to catch quoting, bracket, and portability issues automatically.
bash -n script.sh
shellcheck script.sh

Summary

  • The token after near unexpected token tells you where to look; the real cause is often just above it.
  • Check for CRLF line endings first ($'\r'), then unmatched quotes/parentheses/braces.
  • Keep spaces inside [ ] and around operators; do not forget then/fi/do/done.
  • Run Bash scripts with bash, not sh, and validate with bash -n and ShellCheck.

References

Sponsored Links
Sponsored Links
★ Share on X
Related posts