How to use Conditional Statements on Bash Script (if, elif)

To Use Conditional Statements On Bash Script (if, elif)

Introduction

Conditional statements define “if a condition is true, then do that, otherwise do this instead.” Bash conditionals let you write code that performs different tasks based on specified checks. These checks can be based on a simple assessment that results in a true or false result.

Procedure

Step 1: Check the OS version by using the below command

globalt@linuxhelp:~$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 22.04.3 LTS
Release:	22.04
Codename:	jammy

Step 2: Create a file by using your favourite editor, here I’m using vim editor

globalt@linuxhelp:~$ vim if.sh
Copy the following lines to the file
#!/bin/bash
if [ $UID -eq 0 ]
then
echo "You are root"
fi

Step 3: Give execute permission to the user by using the below command

globalt@linuxhelp:~$ chmod +x if.sh

Step 4: Now run the script from the globalt user by using the below command

globalt@linuxhelp:~$ ./if.sh
There is no output

Step 5: Switch to the root user by using the below command

globalt@linuxhelp:~$ su root
Password:

Step 6: Run the same script form the root user by using the below command

userroot@linuxhelp:/home/globalt# ./if.sh
You are root

Step 7: Exit from the root user by using the below command

root@linuxhelp:/home/globalt# exit
exit

Step 8: Now make some changes in the script by using the below command

globalt@linuxhelp:~$ vim if.sh
Copy the following lines to the file
if [ $UID -eq 0 ]
then
        echo "You are root"
else
        echo "You are not root user"
fi

Step 9: Again run the script from the globalt user by using the below command

globalt@linuxhelp:~$ ./if.sh
You are not root user

Step 10: Now make some more changes in the script by using the below command

globalt@linuxhelp:~$ vim if.sh
Copy the following lines to the file
if [ $UID -eq 0 ]
then
        echo "You are root"
elif [ $UID -eq 1000 ]
then
        echo "You are globalt user"
else
        echo "You are not root user"
fi

Step 11: Again run the script from the globalt user by using the below command

globalt@linuxhelp:~$ ./if.sh
You are globalt user

Conclusion

We have reached the end of this article. In this guide, we have walked you through the steps required to use Conditional Statements on Bash Script (if, elif). Your feedback is much welcome.

FAQ
Q
How to give execute permission to the file?
A
Chmod +x
Q
What is the elif condition in the script?
A
elif condition is used in order to add an additional condition to your statement.
Q
What is the use of the else in the if condition?
A
if the previous conditions are false, execute another command
Q
What is the use of the then-in-if condition?
A
Then is used to execute a specific command, if the previous condition is true.
Q
What is the if condition in the script?
A
If the condition represents the condition that you want to check