Articles

Home / Articles / DevOps / How to add conditions in your Bash Script?

How to add conditions in your Bash Script?

Published on Oct. 27, 2021

To solve a problem there is a high chance that your program needs some condition testing. Depending upon the condition to the condition we execute our program. Similarly in a Bash script, while writing a script we add some testing and then configure the system accordingly.

 

In this article, we are going to discuss how we can add some conditions to our Bash script. In case you don't have knowledge about Bash script and how you can write a simple script follow this article - How to create Simple Bash Script?

 

Table of content

 

What is a Conditional Statement?

A conditional statement lets you add some choice to your script. You can add certain actions on a definite condition.

 

It is like if this... (do this), else... (do this)

 

In a Bash script, the syntax for the conditional statement is 

 

if (condition) 
then
statement ---
else
statement ---
fi

 

To check the condition in Linux we have the following two commands:

 

test expression

 

[ expression ]

 

 The above command provides an exit code by which we can apply the execution of our statements. 

 

What is an Exit code?

In Linux, when we run a command, the command not only returns the output but also provides an exit code for it. This exit code ensures the command is run successfully or not. 

 

In order to check the exit code of any command, we can follow the below command

 

echo $?

 

Exit code has a range of 0-255. Generally, for successfully running a command the exit code is but it is always advisable to check that in the manual of that command.

 

How to add a condition statement in Bash Script?

In our last post on Bash scripting, we have created a simple script that is displaying something, now we will add some conditions to them.

 

For this demonstration, let's create a scenario where we have a script and the user will provide a number while running the script. This script will test and print is it an odd number or an even number.

 

#!/usr/bin/bash
echo -n "Enter a number: "
read num
if [ `expr $num % 2` == 0 ]
then
echo "$num is an even number"
else
echo "$num is an odd number"

 

In the above condition, we have used expr to solve the expression.  Now you can add the required condition to your program. 

 

Note: Sometimes while writing the script we want to check the above command has run successfully or not. And this could be easily done by the concept of exit code and conditional statement. We will cover this demonstration in some advanced articles.

 

Final Voice

In this article, we have discussed what is conditional statement and how we can add conditions to our script. To know more about scripting you can bookmark the page.

 

Connect with the author on Twitter.

 

 

 

···