--- layout: page category-page: scripts category-title: Scripting tags: if else script scripting read author: Matteo Omenetti title: If Statement ---

If statements allow us to make decisions in our Bash scripts. They allow us to whether run or not a piece of code based on a condition that we set.
If statements take this form:

    if [condition]
      then
        command1
        command2
        command3
        ...
      fi
  
Anything between then and fi will be executed only if the condtion evaluates to true.
Here is a simple example:
  i=210;

  if [$i -ge 200]
    then
      echo You chose a big number.
  fi
In this first example we evaluate a varibale i to 105. The if statement will print "You chose a big number" only if the number contained in our varibale i is Greater or Equal to 200.
This is our 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 condtion 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 sattements take this form:
  if [condition]
    then
      command1
      command2
      command3
      ...
    else
      command1
      command2
      command3
      ...
    fi
Here is a simple example:
  i=50;

  if [$i -ge 200]
    then
      echo You chose a big number.
    else
    echo You chose a small number.
  fi
In this example, that is just an extention of the previuous example, we evealuate a variable i to 50. If i is gretaer or equal to 200, you print out "You chose a big number", otherwise, (if i is not gretaer or equal to 200), just like in this case, you 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 condtions that lead to different paths. We can accomodate this need with the if else elif mechanism. The if else elif mechanism takes this form:
  if [condition]
    then
      command1
      command2
      command3
      ...
  elif [condition]
    then
      command1
      command2
      command3
      ...
  else
      command1
      command2
      command3
      ...
  fi
Here is a simple example:
  i=150;

  if [$i -ge 200]
    then
      echo You chose a big number.
  elif [$i == 150]
    then
      echo You chose 150.
  else
    echo You chose a small number
  fi
In this example, that is just an extention of the previuous example, we evealuate a variable i to 150. If i is gretaer 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.