Categories
Linux Tutorial Series

Linux Tutorial Series – 186 – The else statement

Here is the video version, if you prefer it:

The else statement in combination with the if statement is used to tell the following: “If this condition is true do this, if this condition is not true, do that”. That’s pretty much the gist of it.

Below is the entire shell script (with the else statement), modeled after (Ward, 2014)⁠:

#!/bin/bash

if [ “$1” = ‘Hello’ ]

then

echo 'Hello back to you!'

else

echo 'You are rude.'

fi

And let’s run this script with the first argument being Hello and then it being something different:

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh Hello

Hello back to you!

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript.sh argument1

You are rude.

What is happening here? We are testing if the first argument to our script is Hello. If it is, we echo Hello back to you! and if it is not, we echo You are rude.

What happens is the following:

  1. The test in the if condition is tested – that is, we check if $1 really equals Hello.
  2. If the test from step 1 is true (meaning that the exit code is 0), we execute the code starting at then until else – that is, we echo “Hello back to you!”
  3. If the test from step 1 is false (meaning that the exit code is not 0), we execute the code starting at else until fi – that is, we echo “You are rude.”

This process above follows the logic of: “If the condition is true, then this, if not (else), then the other thing”.

Hope you learned something useful!

References

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 256-257