Bash Scripting: How to Use if

Over the last few weeks I have gone through what I consider to be key points and rules over scripting in general, and Bash scripting specifically.

This week, I’ve decided to take a look at one of the most common commands you’ll use, ‘if’

‘if’ statements – What?

In bash scripting, as in the real world, ‘if’ is used to ask a question. The ‘if’ command will return a yes or no style answer and you can script the appropriate response.

The general format for an if statement is:

if [something]
    then
         do option 1
    else
         do option 2
fi

As you may have noticed, I have added a backwards ‘if’ (a ‘fi’) at the end of my statement. This is to close off the ‘if’ argument and is required. For those familiar with html coding is like opening and closing a bold text section using ‘[b]’ bookended with ‘[/b]’.

Nested ‘if’ statements

In addition to a simple ‘if’ statements, you can do something called nested ‘if’s. As the name implies, you can run a second (or more) ‘if’ argument dependant on the result of a first ‘if’ result. The general format will look similar to the following:

if [something]
     then
         if [something]
              then
                    do option 1a
              else
                    do option 1b
        fi
   else
        do option 2
fi

What can I ask with ‘if’?

If is another powerful tool in the Bash scripting tool box and has a very large number of uses. You can try to run a ‘man’ (manual) command but you will be redirected to a page about shell built in commands, with almost no information.
Unfortunately the only resources I have been able to find was by Googling “if bach” followed by what I wanted to do. However recently I have found a nice webpage with not just a number of basic arguments you can chuck through ‘if’, but even more advanced usage.

For example:

if –a [file] – To test if [file] exists.
if –d [directory] – To test if [directory] (otherwise known as a folder) exists.
if –o [file] – To test if [file] is owned by the user running the script.

Thanks to tldp.org

Check out the links section below for other websites that have useful information.

Examples

Ok, now to the reason why you’re here, examples of ‘if’ statements in use!

Example 1:

if –a "/Users/darren/Desktop/Test_File.txt"
    then
    echo "Test_File.txt is present"
    else
    echo "Test_File.txt is NOT present"
fi

This checks if a file called “Test_File.txt” is present in my Desktop folder. If it is, the phrase “Test_File.txt is present” is displayed in the terminal window. If not, the phrase “Test_File.txt is NOT present” is displayed instead.

Example 2:

if –d "/Users/darren/Desktop/Test_Folder"
      then
      echo "Folder is present"
      else
      echo "Test_File.txt is NOT present"
      mkdir "/Users/darren/Desktop/Test_Folder"
fi

This checks if a folder called “Test_Folder” is present in my Desktop folder. If it is, the phrase “Test_Folder is present” is displayed in the terminal window. If not, the phrase “Test_Folder is NOT present” is displayed and the folder created.
This example is useful if an application requires a folder but, for some reason, the folder cannot be created automatically.

Example 3:

if [$? = 0]
      then
      echo "Fine"
      else
      echo "Last command exit code indicated a failure."
fi

This checks if the result of the command run (before ‘if’) gave an exit code of 0. If it did, the phrase “Fine” is displayed in the terminal window. If not, the phrase “Last command exit code indicated a failure.” is displayed.
This example is great for error checking within a script. The use of the $? variable is what the system uses to store the exit code of the last run command. So dotting a few of these error checking codes after important commands is a good idea, with the ‘then’ and ‘else’ carrying out appropriate clean up and/or notification services.

Summary

And that’s it for this week. This little series seems to be going well, and I think a session on ‘grep’ or a general session on pipping commands and variables might be on the cards for next time. However, as always, I’m on the look out for recommendations for future posts, and other peoples opinions and hints.
If this sounds like you, let us know in the comments below and I’ll try to respond to as many as I can.

Links

TLDP’s “Introduction to ‘if’”
Advanced Guide to Bash

3 Replies to "Bash Scripting: How to Use if"

  • Matt

    Good info, but we (programming instructors) need to ensure when we give coding examples to folks that we instill good coding practices such as formatting for readability. I’ll correct one of your examples to be:

    if [[ –d “/Users/darren/Desktop/Test_Folder” ]]; then
    echo “Folder is present”
    else
    echo “Test_File.txt is NOT present”
    mkdir “/Users/darren/Desktop/Test_Folder”
    fi

    which is more readable and hence maintainable–trivial example, but the indentation and is important.

    P.S. I’m a KSH scripter, so I added the [[ and ]]; I don’t know if this if BASH format, but the point remains, some enclosing braces should be used.

    Thanks!

  • Matt

    Errrr…I see the indentation didn’t take hold in the example. Errrr…sorry.

  • Thanks Matt.

    I have to be honest and say these examples were not 100 % tested and dependant on what you are querying and how you are querying it will denote if you need one, two or no sets of square brackets ( “[” and “]”) around the ‘question’.

    In typical scripting, personally I’ll add a lot of comments (using “#” in front, see my first post in this series) and plenty of indentations. Although not required to make a script work, it makes it a damn sight easier to read.
    One of our company used scripts has up to 3 or 4 nested ‘if”s which can get confusing.

    Unfortunately the blog and comments cannot take tab-spaced formatting in text (but I’ll double check with our web guru). I’d be tempted to say to have the examples as images, but then you loose the ability to copy and paste from them.

    Darren

Leave a Reply

Your email address will not be published. Required fields are marked *