Bash If-Then-Else Example

Bash If-Then-Else Example

In this lesson, we will see how we can use If-Then-Else statements in Bash environment scripts we write. If-Then-Else statements are a useful tool to provide a way to define the path of action of a script when some conditions are met. Let us see what is the syntax for If-Then-Else statements:

if SOME-COMMANDS;
then THEN-COMMANDS;
else ELSE-COMMANDS;
fi

In the above command shown, if SOME-COMMANDS is found to be true or its return status is found to be 0, the THEN-COMMANDS will be executed. If this is not the case, ELSE-COMMANDS are executed. In the SOME-COMMANDS, we usually do some String comparison or value comparison in form of integers. We can also do a lot of operations which involves files. Let us look at some example primary commands which are used mainly when working with file-based conditions:

Primary Meaning
[ -a <FILE> ] Returns true when FILE exists.
[ -b <FILE> ] Returns true when FILE exists & is a block special file.
[ -c <FILE> ] Returns true when FILE exists & is a character special file.
[ -d <FILE> ] Returns true when FILE exists & is a directory.
[ -e <FILE> ] Returns true when FILE exists.
[ -f <FILE> ] Returns true when FILE exists & is a regular file.
[ -g <FILE> ] Returns true when FILE exists & its SGID bit is set.
[ -h <FILE> ] Returns true when FILE exists & is a symbolic link.
[ -k <FILE> ] Returns true when FILE exists & its sticky bit is set.
[ -p <FILE> ] Returns true when FILE exists & is a named pipe (FIFO).
[ -r <FILE> ] Returns true when FILE exists & is readable.
[ -s <FILE> ] Returns true when FILE exists and has a size greater than zero.
[ -t <FD> ] Returns true when file descriptor FD is open & refers to a terminal.
[ -u <FILE> ] Returns true when FILE exists & its SUID (set user ID) bit is set.
[ -w <FILE> ] Returns true when FILE exists & is writable.
[ -x <FILE> ] Returns true when FILE exists & is executable.
[ -O <FILE> ] Returns true when FILE exists & is owned by the effective user ID.
[ -G <FILE> ] Returns true when FILE exists & is owned by the effective group ID.
[ -L <FILE> ] Returns true when FILE exists & is a symbolic link.
[ -N <FILE> ] Returns true when FILE exists & has been modified since it was last read.
[ -S <FILE> ] Returns true when FILE exists & is a socket.

The THEN-COMMANDS and the ELSE-COMMANDS can be any valid UNIX operations or any executable program. Note that the then and fi commands are separated by semi-colon as they are considered to be completely separate elements of a script.

If-Then-Else Simple Example

Let us start our lesson with a very simple example with If-Then-Else statements.
Here is a sample program:

If Example

Here is the output we see when we run our script:

$ . ifelse1.sh
Values are same!
$

Using command-line arguments

We can also use command-line arguments in our scripts and use the number of arguments and the values itself as a condition in the IF statement we define. We first define a text file with following content:

My name is LinuxHint. I love servers, especially the Ubuntu ones. They are so
terminalish!

Now, we can write a script which finds if a word occurs in a text file or not. Let’s define the script now:

echo "Finding $1 in $2"
grep $1 $2
if [ $? -ne 0 ]
then
  echo "$1 not found in file $2."
else
  echo "$1 found in file $2."
fi
echo "Script completed."

This script is very dynamic. It considers the word to find and the file to search from command-line itself. Now, we’re ready to run our script:

. ifelse2.sh love hello.txt

We will see an output like:

Finding love in hello.txt
love found in file hello.txt.
Script completed.

Checking number of command-line arguments

Inside an IF statement, we can even check how many command-line arguments were passed to the command so that we can act upon the same:

count=$#
if [ ! $count -gt 1 ]
then
  echo "Not enough arguments"
else
  echo "Good job!"
fi

Let’s run this script now, we will see the following output:

Command line arguments

If-Then-Elif-Else Statements

We can also have multiple IF statements in the same block to narrow down the decision path our program takes to execute commands we defined. Here is the syntax to define multiple IF statements in our scripts:

if TEST-COMMANDS;
then
RESULT-COMMANDS;
elif
ANOTHER-COMMANDS;
then
ANOTHER-RESULT-COMMANDS;
else
ALTERNATE-COMMANDS;
fi

This looks quite familiar though and easy to follow up as well. Let us define a simple example to establish how the tree works:

count=$#
if [ $count -eq 1 ]
then
  echo "Only one argument found."
elif [ $count -eq 2 ]
then
  echo "Better, two arguments found."
else
  echo "Good job, many arguments found!"
fi

Here is what we get back with this command:

If Then Elif Else example

Using case staements

IF-ELSE statements are useful when you have a big list of options you need to decide upon. But in case you want to perform an action only in few cases of exact match with the result, we can use CASE statements in Bash scripts as well. Its syntax looks like:

case EXPRESSION in CASE1) COMMANDS-TO-EXECUTE;
CASE2) COMMANDS-TO-EXECUTE;
CASE2) COMMANDS-TO-EXECUTE;
) COMMANDS-TO-EXECUTE;
*) COMMANDS-TO-EXECUTE;
esac

The last case with * acts as the default case and will be executed when none of the above-defined cases is found to be a match.

Let us quickly construct a simple example using the CASE statements:

case "$1" in
1)
echo "Value is 1."
;;
2)
echo "Value is 2."
;;
3)
echo "Value is 3."
;;
*)
echo "Other value passed."
esac

Each CASE statement is terminated by ;; (double semi-colon marks). Here is what we get back with this command:

CASE example

Conclusion

In this lesson, we looked at how we can use IF-ELSE, IF-THEN-ELIF and CASE statements in the Bash scripts we define to take specific actions on the basis of values which exist in our programs or passed by the user using positional parameters.

Related Posts
Leave a Reply

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