Aditya Aditya - 2 years ago 148
Linux Question

"syntax error near unexpected token `elif'" error in bash

I wrote a script and parts of the script are as follows:


if [ "$1" == "this_script" ] then
this_script --parameters
elif [ "$1" == "other_script" ] then
other_script --parameters
echo "missing argument"

When I run this script, I get the error,

syntax error near unexpected token `elif'
`elif [ "$1" == "SWDB" ] then'

1) Is it an issue with line endings? I wrote the script with Notepad++ on Windows BUT i have enabled the EOL conversions under Edit to UNIX/OSX format.

2) If not line endings, what is the error?

I am running this script in bash shell on a Redhat Linux OS.

Answer Source

You need a semi-colon after if [ ... ] and before then, and the same with elif:

if [ "$1" == "this_script" ]; then
#                           ^
#                           here!
#                              v
elif [ "$1" == "other_script" ]; then

From Bash manual - Conditional Constructs:

The syntax of the if command is:

if test-commands; then
[elif more-test-commands; then
[else alternate-consequents;]

The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If test-commands returns a non-zero status, each elif list is executed in turn, and if its exit status is zero, the corresponding more-consequents is executed and the command completes. If ‘else alternate-consequents’ is present, and the final command in the final if or elif clause has a non-zero exit status, then alternate-consequents is executed. The return status is the exit status of the last command executed, or zero if no condition tested true.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download