Linux Bash Syntax Error Near Unexpected Token
Warningbash errors
Overview
Bash 'syntax error near unexpected token' occurs due to scripting mistakes like mismatched quotes, missing semicolons, or Windows line endings in scripts.
Key Details
- One of the most common bash scripting errors
- The error message points to the token where bash got confused
- Common tokens: '(', ')', 'do', 'done', 'fi', 'then', newline
- Windows carriage returns (\r) are invisible but cause this error
- Missing or extra quotes, brackets, or keywords cause parsing failures
Common Causes
- Script created/edited on Windows containing \r\n line endings
- Missing 'then' after 'if' condition or 'do' after 'for/while'
- Mismatched or unclosed quotes (single or double)
- Missing semicolon before 'then', 'do', or closing keywords
- Copy-pasted code containing smart quotes or invisible Unicode characters
Steps
- 1Check for Windows line endings: cat -A script.sh (look for ^M at line ends)
- 2Convert line endings: dos2unix script.sh or sed -i 's/\r$//' script.sh
- 3Run bash syntax check without executing: bash -n script.sh
- 4Check for unmatched quotes: grep -n '"' script.sh | wc -l (should be even)
- 5Use shellcheck: shellcheck script.sh for comprehensive linting
Tags
linuxbashsyntax-errorscriptingshell
More in Bash Errors
Frequently Asked Questions
Windows uses \r\n (CRLF) while Linux uses \n (LF). The \r character is invisible but bash interprets it as part of the command, causing syntax errors.