Troubleshooting

bash: syntax error near unexpected token: what each token means and how to fix it

Fix bash syntax error near unexpected token: what (, newline, fi, done, then and CRLF mean, unexpected end of file, and how to check a script with bash -n.

Published ~8 min read
On this page

Short answer: bash reads the whole command (or the whole compound block) before it runs anything, and it stops at the first token it cannot place and names it. The token tells you what kind of mistake it is: ( means unquoted parentheses or a bash feature run by sh, newline means a line ended where something was still missing, fi, done or then means a missing ; or an empty block, and $'\r' means Windows line endings.

bash
bash -n script.sh            # parse only, run nothing: shows the first syntax error
file script.sh               # "with CRLF line terminators" = Windows line endings
sed -i 's/\r$//' script.sh   # strip them
head -1 script.sh            # which shell the script asks for (#!/bin/bash or #!/bin/sh)
bash script.sh               # run it with bash, not sh, if it uses bash syntax

How to read the message

Every message on this page came from throwaway scripts on one of our Debian 12 servers, with GNU bash 5.2.15 and dash 0.5.12 (which is /bin/sh on Debian and Ubuntu). A script and an interactive prompt print the same error slightly differently:

output · bash 5.2 and dash
$ bash p1.sh
p1.sh: line 2: syntax error near unexpected token `('
p1.sh: line 2: `cp report(final).txt /tmp/'
$ sh p1.sh
p1.sh: 2: Syntax error: "(" unexpected
$ cp report(final).txt /tmp/        # typed at the prompt
bash: syntax error near unexpected token `('
  • The token between the backtick and the quote is what bash could not fit. It is often not the mistake itself but the first word after it: a missing then is reported at the fi that follows.
  • The line number is where the parser noticed, so look at that line and the lines above it. dash sometimes reports one line later than bash for the same file.
  • The second line (bash only) repeats the source line. When it looks garbled or starts with a stray quote, the line contains a carriage return; see CRLF.
  • Commands above the broken block have already run; the block and everything after it do not. In our runs bash and dash both stopped the script with exit status 2.

Token in the message, usual cause and fix

Each row was reproduced here with bash -n and by running the script.

Token in the messageUsual causeFix
`('Unquoted parentheses in a file name or argument; a bash script (arrays, function f(), <(...)) run with shQuote the word: "report(final).txt"; run with bash
`newline'A placeholder such as <your-ip> pasted from docs; a redirect with no file (echo x >); an HTML page saved as the scriptReplace the placeholder; finish the redirect; check head -c 200 script.sh
`fi'No ; or newline before then, as in if [ ... ]then; an empty then branchif [ ... ]; then; put : in an empty branch
`done'No ; before do; an empty loop bodywhile ...; do; give the loop a command
`then'then after while, for or else; an if with no conditionLoops take do; write elif, not else, before a condition
`else'A then branch that holds only a commentAdd : (the null command) to the branch
`$'\r''Windows (CRLF) line endings; also shown as $'do\r' or $'{\r'sed -i 's/\r$//' script.sh or dos2unix
`}'A function body with an if or loop that was never closedAdd the missing fi or done before }
unexpected end of fileMissing fi, done or }; a trailing | or &&; an unclosed heredocClose the block, finish the pipeline, put the heredoc delimiter alone at column 1

Unexpected token '(': quoting, and sh is not bash

( and ) are shell metacharacters. The GNU bash manual says each metacharacter "must be quoted if it is to represent itself", and POSIX lists ( ) among the characters an application shall quote. A file name such as report(final).txt or photo (1).jpg therefore needs quotes or backslashes; both of these lines pass bash -n:

bash
cp "report(final).txt" /tmp/
cp report\(final\).txt /tmp/

The other big source is a bash script started with sh. On Debian and Ubuntu sh is dash, and dash does not know three bash features that all contain (. Each of these scripts runs fine with bash and fails with sh:

output · sh = dash 0.5.12
$ sh p3.sh                 # hosts=(web1 web2)
p3.sh: 2: Syntax error: "(" unexpected
$ sh p2.sh                 # function greet() {
p2.sh: 2: Syntax error: "(" unexpected
$ sh ps.sh                 # diff <(ls /etc) <(ls /usr)
ps.sh: 1: Syntax error: "(" unexpected

POSIX defines a function as fname ( ) compound-command; it lists function only among the words that "may be recognized as reserved words" with unspecified results, and it treats array assignment as an extension. So the portable function syntax is greet() { ...; }, which both shells accept. If the script needs arrays or process substitution, keep #!/bin/bash and start it with bash script.sh or ./script.sh, never sh script.sh. The same mix-up produces source: not found, and how to run a .sh file compares the ways to start a script.

Unexpected token 'newline': placeholders and redirects

newline means the line ended while bash still waited for a word. The classic case is a documentation placeholder copied as is. < and > are redirection operators, so <your-ip> reads as "input from the file your-ip, then send output to..." and the line ends before the target:

output · bash and dash
$ bash -n n1.sh            # ssh root@<your-ip>
n1.sh: line 2: syntax error near unexpected token `newline'
n1.sh: line 2: `ssh root@<your-ip>'
$ sh -n n1.sh
n1.sh: 3: Syntax error: newline unexpected
$ echo hi > <your-file>     # at the prompt
bash: syntax error near unexpected token `<'

Replace the whole placeholder, angle brackets included: ssh root@203.0.113.10. A redirect with nothing after it (echo "log" >) gives the same message. So does an HTML page saved under the script's name: its first line <!DOCTYPE html> fails with line 1: syntax error near unexpected token `newline', and file install.sh says HTML document. That case is covered in exec format error.

Unexpected token fi, done, then or else

The GNU bash manual gives the forms as if test-commands; then consequent-commands; fi and while test-commands; do consequent-commands; done, and adds that wherever a ; appears in the syntax "it may be replaced with one or more newlines". Without either, then or do is just another argument, and the parser only complains when it reaches the closing word:

output · bash -n and sh -n
# if [ -f /etc/hostname ]then        (also: ] then on one line)
t2.sh: line 4: syntax error near unexpected token `fi'
t2.sh: 4: Syntax error: "fi" unexpected (expecting "then")

# while true do
t6.sh: line 4: syntax error near unexpected token `done'
t6.sh: 4: Syntax error: "done" unexpected (expecting "do")

# for f in *.log do        (do becomes a list item)
t3.sh: line 3: syntax error near unexpected token `echo'
t3.sh: 3: Syntax error: word unexpected (expecting "do")

dash adds what it expected, which is often the quickest hint. The other common causes:

  • An empty block. then followed directly by fi, or a then branch that holds only # TODO before else, fails with `fi' or `else'. A loop with nothing between do and done fails at done. A comment is not a command; put : there.
  • then in the wrong construct. while ...; then and for i in 1 2; then fail at then (loops take do), and so does else [ "$x" = 2 ]; then, which should be elif.
  • A semicolon too many. then; echo found fails with `;': then is already a separator.

Loop syntax with working examples is in the bash for loop guide.

Unexpected token $'\r': Windows line endings

Windows editors end lines with CR LF; Linux uses LF. bash then sees a carriage return glued to the last word of each line. Which token it names depends on that word:

output · bash 5.2, CRLF scripts
$ file c2.sh
c2.sh: Bourne-Again shell script, ASCII text executable, with CRLF line terminators
$ bash c2.sh
c2.sh: line 2: $'\r': command not found
c2.sh: line 3: syntax error near unexpected token `$'do\r''
$ bash -n c5.sh            # greet()<CR> then { on the next line
c5.sh: line 2: syntax error near unexpected token `$'\r''
$ bash -n c1.sh            # if ...; then<CR> ... fi<CR>
c1.sh: line 5: syntax error: unexpected end of file

The last case is the sneaky one: fi\r is not the word fi, so the if never closes and you get "unexpected end of file" with no hint about line endings. In a terminal the repeated source line also looks broken, because the carriage return moves the cursor back to the start of the line. Fix the file, not the code:

bash
grep -c $'\r' script.sh       # how many lines carry a CR
sed -i 's/\r$//' script.sh    # strip the CR at the end of each line
dos2unix script.sh            # the same, if the dos2unix package is installed
file script.sh                # should no longer say CRLF

Scripts written in Notepad on a Windows PC and uploaded to a VPS or dedicated server are the usual source; switch the editor to LF line endings, or convert once after the upload.

Unexpected token '}' and unexpected end of file

Both mean a block was opened and never closed. Inside a function, the parser reaches } while an if or loop is still open; at the top level it reaches the end of the file:

output · bash -n and sh -n
# backup() { if ...; then tar ...   }   (fi missing)
e1.sh: line 5: syntax error near unexpected token `}'
e1.sh: 5: Syntax error: "}" unexpected (expecting "fi")

# for f in *.log; do gzip "$f"         (done missing)
e2.sh: line 4: syntax error: unexpected end of file
e2.sh: 4: Syntax error: end of file unexpected (expecting "done")

# echo "Backup started                  (quote never closed)
e4.sh: line 2: unexpected EOF while looking for matching `"'
e4.sh: 4: Syntax error: Unterminated quoted string

bash points at the line after the end of the file, so count your openers instead: every if needs a fi, every do a done, every case an esac, every { a }. An apostrophe inside single quotes (echo 'it's done') opens a new quote; use double quotes around it.

A heredoc whose closing word is indented (with spaces, or with tabs without <<-) is never closed. bash only warns here-document at line 3 delimited by end-of-file (wanted `END') and swallows the rest of the file, so a fi after it vanishes and you get unexpected end of file. Put the delimiter alone at the start of its line.

The general method: bash -n, bash -x, ShellCheck

  • Check which shell runs it. head -1 script.sh shows the shebang. ./script.sh uses that line; sh script.sh ignores it and uses dash; cron jobs and the shell form of a Dockerfile RUN line also hand their command to /bin/sh. If the error disappears with bash script.sh, the script needs bash.
  • bash -n script.sh parses the file without running it (bash's help set: "Read commands but do not execute them"). sh -n script.sh does the same with dash. It finds syntax errors only: a typo like [-f passes and fails at run time as [-f: command not found.
  • bash -x script.sh prints each command after expansion with a + in front. It helps once the syntax is fine and the script still does the wrong thing.
  • ShellCheck is a static analysis tool for shell scripts. Paste the script at shellcheck.net, or install the shellcheck package (Debian 12 ships 0.9.0). It names many of the causes above directly, for example SC1017 "Literal carriage return" for CRLF files, and warns about bash features in a #!/bin/sh script (the SC3xxx checks, which replaced SC2039 in ShellCheck 0.7.2).

The same errors appear at login when ~/.bashrc has one: bash prints -bash: /root/.bashrc: line N: syntax error near unexpected token ... and skips the rest of the file. Run bash -n ~/.bashrc and see fixing a broken .bashrc.

Sources: GNU bash manual, Conditional Constructs, Looping Constructs and Quoting; POSIX Shell Command Language (2024 edition).

Frequently asked

What does syntax error near unexpected token mean in bash?

bash parses a command or a whole if, loop or function before running it, and stops at the first word that cannot appear at that point. The quoted token is that word, which is often just after the real mistake, such as a fi after a missing then. Run bash -n script.sh to see the error without running anything.

How do I fix syntax error near unexpected token `('?

Quote the word that contains the parentheses, for example cp "report(final).txt" /tmp/. If the script uses arrays, function f() or <( ) process substitution, run it with bash script.sh instead of sh script.sh, because sh is dash on Debian and Ubuntu and does not support them.

Why do I get syntax error near unexpected token `$'\r''?

The script has Windows line endings, so every line ends with a carriage return that bash treats as part of the last word. file script.sh then reports CRLF line terminators. Run sed -i 's/\r$//' script.sh, or dos2unix script.sh if it is installed, and run the script again.

What causes syntax error: unexpected end of file?

A block was opened and never closed: a missing fi, done, esac or closing brace, an unclosed quote, or a heredoc whose end word is indented. A script with Windows line endings also triggers it, because fi followed by a carriage return is not the keyword fi. bash -n script.sh confirms the error; count each opener against its closer.

Related articles

All troubleshooting