Skip to main content
Bash Scripting

BASH IF Statement

By July 18, 2016September 12th, 2022No Comments

Working With a Simple BASH IF Statement

Let’s look at how we can use the BASH IF Statement with a couple or worked examples.

18-07-2016-17-16-45-300x109

In this blog we look at a couple of examples of using the BASH IF Statement. We will keep if simple to start with using just the BASH IF conditional and not looking at else or elif. As usual we will also provide a video at the end demonstrating the scripts that we use.


To start with we can use BASH to search for user in the the account database file /etc/passwd. With this we can look at the Boolean value ( true or false ) that is returned by the command grep rather than looking at the output. We only want this Boolean value when looking at conditionals and this includes the BASH IF statement. To search for the user we are going to use the command grep.

grep -q tux /etc/passwd

The -q option is great to use here as it suppresses the output of grep, we just want to see the true or false nature when the command was run and not the matched lines. For us to see the Boolean return value we will need to use something like:

echo $?

After running the command to see if it is true or false but for the BASH IF statement this is the natural territory in which it works.

if grep -q tux /etc/passwd ; then
  echo "Tux is in the house"
fi

We can see how simple the statement can be and is closed by the word fi . This is the word if in reverse.

If we need to look at the actual output of a command rather than just its success or failure then we will have to use the command test or its synonym [.

if [ $(date +%m) -eq 07 ] ; then
  echo "It is summer"
fi

Using the option +%m with date will just display the month number. 07 will be July and then we can print that it is the Northern Hemisphere summer if it is 07. As we want to assess the out put of the command we now use square brackets for our test. -eq is used to test numeric equivalence and == string equivalence.

This video steps you through the process.


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

shellscripting