>If statement_
If statements allow us to make decisions in our Bash scripts. They allow us to
decide whether or not to run a piece of code based on a condition that we set.
If statements take this form: Anything between
Here is a simple example: In this first example we evaluate a variable
This is the case, therefore the output of this piece of code will be:
If statements take this form: Anything between
then
and fi
will be executed only if the condition
evaluates to true. Here is a simple example: In this first example we evaluate a variable
i
to 105.
The if statement will print "You chose a big number"
only if the number contained in our variable i
is Greater or
Equal to 200. This is the case, therefore the output of this piece of code will be:
You chose a big number.
If Else
Sometimes we want to perform a certain set of actions, if our condition evaluates to true and another set of actions if our condition evaluates to false. We can do this with the if else statement. if else statements take this form: Here is a simple example: In this example, which is just an extension of the previous example, we evaluate a variablei
to 50. If i
is greater or equal to
200, we print out "You chose a big number", otherwise,
(if i
is not greater or equal to 200), just like in this case, we print out
"You chose a small number".
Therefore, the output of this piece of code is:
You chose a small number.
If Elif Else
Sometimes, in programming, it is necessary to have a series of conditions that lead to different paths. We can accommodate this need with the if else elif mechanism. The if else elif mechanism takes this form: Here is a simple example: In this example, which is just an extension of the previous example, we evaluate a variablei
to 150. If i
is greater or equal to 200,
you print out "You chose a big number", if i
is equal to 150 you print out
"You chose 150" otherwise you print out "You chose a small number".
Therefore, the output of this piece of code is:
You chose 150.