Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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    $timezone_string="Z" elif[ "$seconds" -gt 0 ] then    $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60` else    echo "Unknown parameter" fi 
like image 243
StuStirling Avatar asked Apr 16 '13 10:04

StuStirling


People also ask

Does Elif work in bash?

Example 1: Basic Bash Else If (elif) In the first if expression, condition is false, so bash evaluates the expression for elif block. As the expression is true, the commands in the elif (else if) block are executed.

Can you do else if in bash?

Bash allows you to nest if statements within if statements. You can place multiple if statements inside another if statement.

What does Elif mean in bash?

IF, ELSE or ELIF (known as else if in other programming) are conditional statements which are used for execution of different-2 programmes depends on output true or false. All the if statements are started with then keyword and ends with fi keyword.


1 Answers

There is a space missing between elif and [:

elif[ "$seconds" -gt 0 ] 

should be

elif [ "$seconds" -gt 0 ] 

All together, the syntax to follow is:

if [ conditions ]; then    # Things elif [ other_conditions ]; then    # Other things else    # In case none of the above occurs fi 

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).

like image 119
fedorqui 'SO stop harming' Avatar answered Dec 09 '22 19:12

fedorqui 'SO stop harming'