Bash Scripting Conditionals

Post Written by
Bojan Vujanić
Last modified on July 2nd, 2020 at 12:24 pm

After we nailed down the part with variables, let's move on to bash scripting conditionals. Conditional statements (branching) help our script execute commands based on tests. With conditional statements, we determine which part of the code (branch) will execute. The basic statement used for branching would be the IF statement. Branching in bash differs from that used in other programming and scripting languages. Bash uses status codes (see Variables post) to decide whether an IF statement will execute. Only if a previous command returns a status code of 0, will the IF statement run. Other languages use Boolean values (True/False) for the same logic.

Bash Scripting IF & Else Statements

An basic IF statement in Bash looks like:

if someCommand; then
#execute the following code if command "someCommand" returns an exit code 0
fi

This example will run all the code between if and fi, only when the someCommand returns a status code of "0". For other cases we want to cover when the someCommand returns a status code other than "0", we use the ELSE statement. To show this works, let's use a GREP command that returns a status code "0" after finding a particular string in a file:

[bizzarec@localhost ~]$ cat luke.txt No, I am your father
[bizzarec@localhost ~]$ grep "father" ./luke.txt No, I am your father
[bizzarec@localhost ~]$ echo $? 0
[bizzarec@localhost ~]$ grep "mother" ./luke.txt
[bizzarec@localhost ~]$ echo $? 1

Using our knowledge of GREP, let's create a script, within the same directory as the luke.txt file, using:

#!/bin/bash
if grep -q "father" ./luke.txt; then
     echo "Nooo!"
else
     echo "?!"
fi

Running the above will print "Nooo!" if it finds the string "father" in the file luke.txt, otherwise it will print "?!". IF and ELSE statements are very useful for comparison, like comparing:

  • a variable to a number
  • a variable to a string
  • if a file or directory exists

Using the TEST command in Bash

As the IF statement executes only when the returned status code is "0", a good command to run comparisons is TEST. With TEST you get easy access to comparison and file test operations like:

test -f /var/www/html/index.html > Returns "0" if index.html exists
test -d /etc > Returns "0" if etc directory exists
test ! -d /root > > Returns "0" if root directory doesn't exist
test 1 -eq 1 > > Returns "0" if numeric comparison succeeds
test ! 1 -eq 0 > Returns "0" if numeric comparison fails
test "potatoe" = "potatoe" > Returns "0" if string values are same
test "potatoe" != "potato" > Returns "0" if string values are different

TEST command comes with other kinds of comparison options like greater than / lower than... More examples can are available on the TEST command manual pages. When working with the TEST command, two things are worth noting:

Integers vs. Strings

The TEST looks different at integers and strings. For example, 007 and 7 are the same by numeric but different by string comparison:

[bizzarec@localhost ~]$ test 007 -eq 7
[bizzarec@localhost ~]$ echo $? 0
[bizzarec@localhost ~]$ test 007 = 7
[bizzarec@localhost ~]$ echo $? 1

TEST command alias

The TEST command is often used, so you can use a "[" (left square bracket), as a shortened alias of the command. So you can write the following in two ways:

[bizzarec@localhost ~]$ test 1 -eq 1
[bizzarec@localhost ~]$ echo $? 0

or

[bizzarec@localhost ~]$ [ 1 -eq 1 ]
[bizzarec@localhost ~]$ echo $? 0

Note: When using "[" command, make sure to have a closing bracket "]" too.

Multi-comparisons using IF statements

IF statements can consist of multi-comparison, handled by the ELIF statement:

#!/bin/bash
QUESTION=$1
if [ "$QUESTION" = "What is my purpose ?" ]; then
echo "You pass butter."
elif [ "$QUESTION" = "Who am i ?" ]; then
echo "You are a robot"
else
echo "42"
fi

In the above example, a variable is passed to the script, then gets assigned to internal script variable QUESTION. Then, based on the variables value, the script echoes out one of the outputs. Since IF/ELIF/ELSE complicate things, you can use switch-case statements when handling multi-comparisons, for example:

#!/bin/bash
case "$1" in
"Chef"|"Puppet")
echo "Ops"
;;
"Python"|"PHP")
echo "Scripter"
;;
"C"|"C++")
echo "Nutjob"
;;
*)
echo "Pick a language !"
esac

So, a variable gets pattern-matched trough all the cases, where each case terminates with parenthesis ")". The first case matches the Chef or Puppet strings. Note how multiple operations are separated with the vertical bar "|", representing the OR operator in many programming languages. Following are the commands to execute in case the variable does match a given value, and the whole case terminates with two semicolons ";;". The sequence ends with a "*)", where "*" matches anything, so ensuring that, if all other cases fail, the last action gets executed. Statements are important in scripting, only IF you have a solid knowledge, you can have your scripts execute commands IF necessary. Stay with us, as there is more to come.

Contact Us

Fill out the enquiry form and we'll get back to you as soon as possible.