Dave Dave - 7 months ago 136
Bash Question

Getting "syntax error near unexpected token `else’" in shell script

I’m using bash shell on Amazon Linux. When I run the below block of code

if [ $rc -eq 0 ] then
passed=`tr ' ' '\n' < $TFILE | grep -c PASSED`
error=`tr ' ' '\n' < $TFILE | grep -c ERROR`
warning=`tr ' ' '\n' < $TFILE | grep -c WARNING`
subject="Automated Results - $passed passed, $error errors, $warning warnings."
else
subject="Failed to run any tests."
fi


I get the error, “syntax error near unexpected token `else’”. What do I need to do to write this if-then-else block correctly?

Answer

To quote the syntax definition from help if in bash (which is quite close to the relevant POSIX spec):

if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi

There can be multiple commands used in the conditional part of an if statement, and a command separator (represented as a semicolon here) is mandatory between the last of them and the list of commands to given should that conditional part return a successful status.


Comparing the code given against that syntax definition, it's missing such a separator:

if [ $rc -eq 0 ]; then
#               ^
#               \- this semicolon, or a newline, is mandatory before "then"

As it is, then is being passed as an argument to the [ command, not parsed as syntax.

(Since you're tagged bash, consider also using native math syntax: if (( rc == 0 )); then is both more readable and less buggy).

Comments