Linux and Networking

Linux and Networking

4.5 Conditional sentences

Imagine that you are selling movie tickets. If someone comes to you speaking in Spanish you answer them in Spanish and if they talk to you in another language you answer them in English because imagine that it is the only language you know besides Spanish.

 

That translated into shell script commands would be something like the following:

 

if [speaking_in_Spanish]; then

       I answer_in_Spanish

else

       I answer_in_english

fi

 

Actually answer_in_Spanish and answer_in_English do not exist in shell script but instead of what I have invented we could ask for the value of some variable or ask if any variable has any value or is null, etc.

 

In shell script there are three different types of conditional statements:

 

Conditionals:

 

  • if expression then statement
  • if expression then statement1 else statement2
  • if expression then statement1 else if expression2 then statement2 else statement3

 

Let’s see below some examples of conditional statements in shell script:

 

#!/bin/bash

# This is an example of if expression then statement

if [ “alboran” = “alboran” ]; then

        echo “True, alboran == alboran”

fi

 

This is another example but using the pattern if expression then statement1 else statement2

 

#!/bin/bash

if [ “alboran” = “alboran” ]; then

echo “True, alboran == alboran”

else

echo “It was false”

fi

 

Remember.

Be careful with white spaces. Try to respect the white spaces in the expressions because otherwise when executing your shell script you may have problems.

 

Let’s see another example now using variables and conditional statements:

 

#!/bin/bash

T1=”sea of”

T2=”dawn”

if [ $T1 = $T2 ]; then

echo “True, ” $T1 ” == ” $T2

else

echo “Not true”

fi

 

Suggested exercises.

  1. Copy and execute the previous exercise. Check that it works and modify it so that T1 is equal to T2. Check now that it says “True…”.
  2. Create a new shell script that says whether the user running it is root or not (remember that with the “echo $USER” command I can know the name of the current user).
The Demeter Project