if, elif, else statement issues in Bash


I can't seem to work out what the issue with the following if statement is in regards to the elif and then. Keep in mind the printf is still under development I just haven't been able to test it yet in the statement so is more than likely wrong.

The error I'm getting is:

./timezone_string.sh: line 14: syntax error near unexpected token `then'
./timezone_string.sh: line 14: `then'

And the statement is like so.

if [ "$seconds" -eq 0 ];then
elif[ "$seconds" -gt 0 ]
   $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
   echo "Unknown parameter"

This question is tagged with bash if-statement

~ Asked on 2013-04-16 10:30:37

The Best Answer is


There is a space missing between elif and [:

elif[ "$seconds" -gt 0 ]

should be

elif [ "$seconds" -gt 0 ]

As I see this question is getting a lot of views, it is important to indicate that the syntax to follow is:

if [ conditions ]
# ^ ^          ^

meaning that spaces are needed around the brackets. Otherwise, it won't work. This is because [ itself is a command.

The reason why you are not seeing something like elif[: command not found (or similar) is that after seeing if and then, the shell is looking for either elif, else, or fi. However it finds another then (after the mis-formatted elif[). Only after having parsed the statement it would be executed (and an error message like elif[: command not found would be output).

~ Answered on 2013-04-16 10:34:25


You have some syntax issues with your script. Here is a fixed version:


if [ "$seconds" -eq 0 ]; then
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
   echo "Unknown parameter"

~ Answered on 2013-04-16 10:36:11

Most Viewed Questions: