OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Missing Or Unexpected Tokens

Another common mistake is forgetting to complete a compound command, such as if or while. Let’s look at what happens if we remove the semicolon after the test in the if command:



#!/bin/bash


# trouble: script to demonstrate common errors number=1

if [ $number = 1 ] then

echo "Number is equal to 1." else

echo "Number is not equal to 1."

fi

#!/bin/bash


# trouble: script to demonstrate common errors number=1

if [ $number = 1 ] then

echo "Number is equal to 1." else

echo "Number is not equal to 1."

fi


The result is this:



[me@linuxbox ~]$ trouble

/home/me/bin/trouble: line 9: syntax error near unexpected token

`else'

/home/me/bin/trouble: line 9: `else'

[me@linuxbox ~]$ trouble

/home/me/bin/trouble: line 9: syntax error near unexpected token

`else'

/home/me/bin/trouble: line 9: `else'


Again, the error message points to an error that occurs later than the actual problem. What happens is really pretty interesting. As we recall, if accepts a list of commands and evaluates the exit code of the last command in the list. In our program, we intend this list to consist of a single command, [, a synonym for test. The [ command takes what follows it as a list of arguments; in our case, four arguments: $number, 1, =, and ]. With the semicolon removed, the word then is added to the list of arguments, which is syntactically legal. The following echo command is legal, too. It’s interpreted as another command in the list of commands that if will evaluate for an exit code. The else is en- countered next, but it’s out of place, since the shell recognizes it as a reserved word (a word that has special meaning to the shell) and not the name of a command, hence the er- ror message.


Top OS Cloud Computing at OnWorks: