Skip to main content
Bash Scripting

Extending BASH IF Statements

By July 20, 2016September 26th, 2016One Comment

Next Step: Extending BASH IF Statements


Now that we have seen how to create and use IF statements, let’s  now dive into extending BASH IF Statements with elif and else. When using BASH instead of using the English term “else if” we abbreviate this to elif. When reading the script back you will read this as meaning else if and allow for more than one condition to be tested.

In the example we use we can pass an inout argument through to the script. This is the variable $1. The value of this can be:

  • directory
  • link
  • file

We can then test for the variable being one of these values so we will need three conditions and the idea of extending BASH IF statement to allow for elif. We can also use the catch all option at the end with else, so if the value passed into the variable is not anything we know about we can display a simple help message back to the user.

If we write the code as simple English it would be something like this:

if the value is this then do this
else if it is then then do this
else if it is this then do this
else just do this
fi

Of course though we cannot write in English and expect BASH to know what we are saying, so we have to speak BASH to the the shell, like this:

#!/bin/bash
#This file was created on 19/02/13

if [[ $1 = "directory" ]]
  then
     find /etc -maxdepth 1 -type d
 elif [[ $1 = "link" ]]
  then
     find /etc -maxdepth 1 -type l
 elif [[ $1 = "file" ]]
  then
     find /etc -maxdepth 1 -type f
 else
        echo "Usage: $0 file | directory | link "
fi

Do remember make careful note that the conditional test and the word then follows the elif statement, as well as the awkward spelling. For each test we make we check the first input parameter to the script, $1, to see if it is directory, link or file and run the appropriate find command. If we do not match on anything then we echo out simple usage instructions, $0 being the name of the script itself.




My Book on Shell Scripting is available from good book shops and the publisher Packt.

shellscripting

Leave a Reply