facebook youtube pinterest twitter reddit whatsapp instagram

Creating Conditional Statements Using if And Else (Bash)

We have recently explored command-line list, we also dived into the test shell builtin command, which can not only be used to check file types but can also be used to compare values. The issue with using those conditions is that aren't easy to read, and it would become difficult to maintain if the complexity of the tasks increases.

In this guide, we would learn how to use if statement to make our script more readable and logical, well, since that is how we think, it can make things a bit easier for us.

The caveat is that it can make the script longer, but since we can achieve more, it doesn't hurt to use if statement. Consider the following, before and after:

Without If:

#!/bin/bash
test -z $1 || echo "Hello $1"
exit 0

With If:

#!/bin/bash
if [ $# -gt 0 ] ; then
    echo "Hello $1"
    exit 0
fi
    echo "Instruction: $0 <firstname>"
    exit 1

if [ $# -gt 0 ] - '$#' Can be used to get the total number of arguments passed to script,, we then check if the value is gt (greater than) zero, we are basically checking if the argument is set, or the user passed a first positional parameter, we then echo it:

echo "Hello $1", this is the output if I supplied the expected input:

user@server:~/bin$ isset2.sh Devsrealmer
Hello Devsrealmer

The end of the if block is denoted with fi - if backwards, If you just run the script as is, without passing the argument, you would get the instructional statement, which assist you on how to use the script, see example:

user@server:~/bin$ isset2.sh
Instruction: /home/user/bin/isset2.sh <firstname>

This ensure that we only display the Hello message if we have supplied a name to be welcomed. You might wonder what the exit 1 and exit 0 does:

The exit is used to reflect the true status of the script, 0 stands for success, and anything other than zero stands for failure, so when used, it ensures you are stoping the execution of our script when a condition is satisfied. Imagine, I didn't use the exit 0 when the condition is satisfied, say, I have something like so:

#!/bin/bash
if [ $# -gt 0 ] ; then
    echo "Hello $1"
    # I didn't add a successful exit here
fi
    echo "Instruction: $0 <firstname>"
    # I didn't add a failed exit here

Now, even if I supplied the right input, I'll still get the instructional statement:

user@server:~/bin$ isset2.sh Devsrealmer
Hello Devsrealmer
Instruction: /home/user/bin/isset2.sh <firstname>

Why so?

This is because I am not telling the script when to exit successfully, it just keeps running! So, by employing exit status,it  ensures you are stoping the execution of the script at the right time.

Another way of writing the script is as follows:

#!/bin/bash
if [ $# -lt 1 ] ; then
    echo "Instruction: $0 <firstname>"
    exit 1
fi
    echo "Hello $1"
    exit 0

The only difference is the way we are checking if the variable is set, and the exit status.

Extending if with else

If condition ; then
    statement
else
    statement
fi

There are cases where a script would be required to continue regardless of the result of the if condition. What to do when
it is true, as well as, false. This is where the else keyword comes to play, it allows the execution of one block of code when the condition is true and another when the condition is evaluated as false.

Let's build on how earlier script, using if and else:

#!/bin/bash

if [ $# -lt 1 ] ; then
        read -p "Enter a Name: "
        name=$REPLY

else name=$1
fi

echo "Hello $name"
exit 0

The following script extend the options for passing name to the arguments, you can either use the script name and the value, e.g:

user@server:~/bin$ isset3.sh Devsrealmer
Hello Devsrealmer

or just run the script, and follow the prompt, so, we have following output:

user@server:~/bin$ isset3.sh
Enter a Name: Devsrealmer
Hello Devsrealmer

Related Post(s)

  • sed (Stream Editor) In Bash Scripting

    Another powerful filter in GNU/Linux is sed (stream editor), which is a program for performing basic editing tasks on the output of another program or on a file. sed or stream editor can be used to p

  • awk In Bash Scripting

    Up until now, we have covered a couple of text processing, from sed to grep to sort, and now we have the big daddy, which is awk. awk (which stands for Aho, Weinberger, and Kernighan - its creators)

  • (Bash Script) Automate Multiple Classicpress & Wordpress Installation + [Caching and SSL]

    If you are tired of using control panels (I am because they are mostly not secure, and most comes loaded with bundles of useless stacks), and want to do everything on the server level, I wrote a menu

  • Returning Values From Functions in (Bash)

    In the guide function in bash, we dive deep in bash functions and we also pass some information into the functions to carry out a certain operation. In this guide, I'll show you how to get informatio

  • Functions in Bash

    Functions are modular building blocks for creating powerful and modular scripts, using function makes it easy to isolate a code since it would be in a single building block, which would be isolated f

  • grep (Regular Expression) In Bash Scripting

    We recently discussed filters in bash scripting, in this guide we would look more into the practical usage of using a filter program, and an example of such a program is grep. grep, in its simplest f