Categories
Linux Tutorial Series

Linux Tutorial Series – 185 – The if statement

Here is the video version, if you prefer it:

The if statement allows us to test for a condition and execute a certain set of commands based on the result of that test. (“If Statements!,” n.d.)⁠

An example script:

#!/bin/bash

if [ "$1" = 'Hello' ]

then

echo 'Hello back to you!'

fi

What is happening here? We are testing if the first argument to our script is Hello. If it is, we echo Hello back to you! and if it is not, we don’t do anything.

More technically, the [ is a command that performs tests for Unix conditionals. (Ward, 2014)⁠ The if, then and fi are shell keywords and everything else is a command. So what happens is that we check if the first argument to our shell script is indeed equal to Hello. If it is, then we echo Hello back to you!. If it is not, we don’t echo out anything.

A detail – the [ command returns an exit code. If the exit code is 0 (as we learned) that means that the check went well and we go on to echo Hello back to you! and if the exit code is non-zero we know that something went wrong and we don’t echo out anything.

Another detail: why did we surround the $1 in quotes above? Because if we don’t pass the first argument (it is empty), we get an error like so:

mislav@mislavovo-racunalo:~/Linux_folder$ ./tutorialScript2.sh

./tutorialScript2.sh: line 2: [: =: unary operator expected

because we don’t supply anything for the missing argument and then we have a gap between the [ and the =. However, when we surround the argument with quotes and don’t supply the argument, we get a so-called empty string (meaning empty sequence of characters). If we use the quotes, we don’t get that error.

Hope you learned something useful!

References

If Statements! (n.d.). Retrieved March 7, 2020, from https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php

Ward, B. (2014). How Linux Works: What Every Superuser Should Know (2nd ed.). No Starch Press. Pages 256-257

NewsletterUpdates on interesting things I am doing

Subscribe to my newsletter to keep abreast of the interesting things I'm doing. I will send you the newsletter only when there is something interesting. This means 0% spam, 100% interesting content.

Leave a Reply

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