BASH Programming

How to Master Conditional Logic in Bash

The use of conditional logic is a very essential part of any programming language. The conditional logic can be implemented in Bash in different ways to solve the programming problems. The methods of using conditional logic in Bash through the different types of “if” and “case” statements to compare the string and numeric values, checking the variable content, checking the existence of the file or directory, etc. are shown in this tutorial.

List of Content:

  1. Use of the “If” Statement
  2. Use of the “If-Else” Statement
  3. Use of the “If-Elif-Else” Statement
  4. Use of the “If” Statement to Check an Empty Variable
  5. Use of the “If” Statement with Logical Operator
  6. Use of the Nested “If” Statements
  7. Use of the “If” Statement to Check the File Existence
  8. Use of the “If” Statement to Check the Directory Existence
  9. Use of the “If” Statement with Regex
  10. Use of the “Case” Statement

Use of the “If” Statement

This example shows the simple use of the “if” statement in Bash. Six types of comparison operators can be used to compare the numeric values in Bash. These are “-eq” (equal), “-ne” (not equal), “-le” (less than equal), “-ge” (greater than equal), “-lt” (less than), and “-gt” (greater than). The uses of “-lt” and “-eq” are shown in the following script whether the number is less than 99 or has not been checked using the “-lt” operator. The number is even or odd and is checked by the “-eq” operator.

#!/bin/bash

#Assign a numeric value

((number=50))

#Check the numeric value using 'if' statement

if [ $number -lt 99 ]

then

echo "Number is valid."

fi

#Check whether the number is even or not

if [ $(( $number % 2 )) -eq 0 ]

then

echo "Number is even."

fi

Output:

The following output appears after executing the previous script:

p1

Go to top

Use of the “If-Else” Statement

The use of the “if-else” statement is shown in the following script. A string value is taken from the user and checks whether the value is “BLUE” or not using the “if-else” statement.

#!/bin/bash

#Take a string value from the user

read -p "Enter your favorite color:" color

#Check the string value using 'if-else' statement

if [ ${color^^} == 'BLUE' ]

then

echo "Fine, Blue color is available."

else

echo "$color is not available."

fi

Output:

The following output appears after executing the previous script if “red” is taken as input:

p2-1

The following output appears after executing the previous script if “blue” is taken as input:

p2-2

Go to top

Use of the “If-Elif-Else” Statement

The use of the “if-elif-else” statement is shown in the following script. A number is taken from the user and checked with the different values until any match is found. If any match is found, the corresponding message is printed. If no match is found, the default message is printed.

#!/bin/bash

#Take the id value from the user

read -p "Enter your serial number:" serial

#Check the input value using the 'if-elif-else' statement

if [ $serial == '4523' ]

then

echo "You are selected in group A."

elif [ $serial == '8723' ]

then

echo "You are selected in group B."

elif [ $serial == '3412' ]

then

echo "You are selected in group C."

else

echo "You are not selected".

fi

Output:

The following output appears after executing the script with the value of 8723:

p3-1

The following output appears after executing the script with the value of 9078:

p3-2

Go to top

Use of the “If” Statement to Check an Empty Variable

The method of checking whether a variable is empty not using an “if” statement is shown in the following script. The “-z” option is used in the “if” statement to do this task.

#!/bin/bash

#Take the id value from the user

read -p "Enter your serial number:" serial

#Check whether the variable is empty or not

if [ ! -z $serial ]

then

#Check the input value using 'if-elif-else' statement

if [ $serial == '690' ]

then

echo "You are selected in team-1."

elif [ $serial == '450' ]

then

echo "You are selected in team-2."

else

echo "You are not selected".

fi

else

echo "No serial number is given."

fi

Output:

The following output appears after executing the script with the value of 690:

p4-1

The following output appears after executing the script if no input value is taken:

p4-2

Go to top

Use of the “If” Statement with Logical Operators

Three types of logical operators can be used in the Bash conditional statement. These are logical OR (||), logical AND (&&), and logical NOT (!). A code value is taken from the user. If the input value is non-empty, the value is checked with two code values using logical OR. If the value matches with any code, the corresponding message is printed. If no matching code is found, the default message is printed.

#!/bin/bash

#Take the course code from the user

read -p "Enter the course code:" code

#Check whether the variable is empty or not

if [ ! -z $code ]

then

#Check the input value using the 'if-elif-else' statement

if [[ $code == 'CSE-106' || $code == 'CSE-108' ]]

then

echo "CSE course."

elif [[ $code == 'BBA-203' || $code == 'BBA-202' ]]

then

echo "BBA course."

else

echo "Invalid course code."

fi

else

echo "No course code is given."

fi

Output:

The following output appears after executing the script with the input value of “CSE-108”:

p5-1

The following output appears after executing the script with the input value of “BBA-56”:

p5-2

 

Go to top

Use of the Nested “If” Statements

When an “if” condition is used inside another “if” condition, it is called a nested “if” statement. The method of using the nested “if” is shown in the following script. Two mark values are taken from the user. If the input values are non-empty, the first “if” condition checks whether the value of “$theory” is greater than or equal to 60 or not. If the first “if” condition returns “true”, the second “if” condition checks whether the value of the “$lab” is greater than or equal to 50 or not. If the second “if” condition also returns “true”, a success message is printed. Otherwise, a failure message is printed.

#!/bin/bash

#Take the theory mark

read -p "Enter the theory mark:" theory

#Take the lab mark

read -p "Enter the lab mark:" lab

#Check whether the variables are empty or not

if [[ ! -z $theory && ! -z $lab ]]

then

#Check the input values using a nested 'if' statement

if [ $theory -ge 60 ]

then

if [ $lab -ge 50 ]

then

echo "You have passed."

else

echo "You have failed."

fi

else

echo "You have failed."

fi

else

echo "Theory or lab mark is empty."

fi

Output:

The following output appears if both or one of the input values are empty:

p6-1

The following output appears if 78 is taken as theory marks and 45 is taken as lab marks. Here, the second “if” condition returns “false”:

p6-2

The following output appears if 67 is taken as theory marks and 56 is taken as lab marks. Here, both “if” conditions return “true”:

p6-3

The following output appears if 50 is taken as theory marks and 80 is taken as lab marks. Here, the first “if” condition returns “false”:

p6-4

Go to top

Use of the “If” Statement to Check the File Existence

The existence of the file can be checked by the bash script in two ways. One is using the “-f” operator with “[]” brackets. Another is using the “test” command and the “-f” operator. A filename is taken and checks the existence of the file using the “if” condition with the “-f” operator. Then, another filename is taken and check the existence of the file using the “if” statement with the “test” command and the “-f” operator.

#!/bin/bash

#Take the filename

read -p "Enter a filename:" fn1

#Check whether the file exists or not without using `test`

if [ -f $fn1 ]

then

echo "$fn1 file exists."

else

echo "$fn1 file does not exist."

fi

#Add newline

echo

#Take another filename

read -p "Enter another filename:" fn2

#Check whether the file exists or not using `test`

if test -f $fn2; then

echo "$fn2 file exists."

#Check whether the file is empty or not using `test`

if test -z $fn2; then

echo "$fn2 file is empty."

else

echo "$fn2 file is not empty."

fi

else

echo "$fn2 file does not exist."

fi

Output:

The following output appears after executing the script by taking the “test.txt” and “testing.txt” as the filenames. According to the output, both files exist in the current location and the “testing.txt” file is empty:

p7-1

The following output appears after executing the script by taking the “f1.txt” and “test.txt” as the filenames. According to the output, the “f1.txt” file does not exist in the current location and the “test.txt” file is not empty:

p7-2

Go to top

Use of the “If” Statement to Check the Directory Existence

The existence of the directory can be checked by the Bash script in two ways like the file. One is using the “-d” operator with “[]” brackets. Another is using the “test” command and the “-d” operator. A directory name is taken and checks the existence of the directory using the “if” condition with the “-d” operator. Then, another directory name is taken and checks the existence of the file using the “if” statement with the “test” command and the “-d” operator.

#!/bin/bash

#Take a directory name

read -p "Enter a directory name:" dir1

#Check whether the directory exists or not without using `test`

if [ -d $dir1 ]

then

echo "$dir1 directory exists."

else

echo "$dir1 directory does not exist."

fi

#Add newline

echo

#Take another directory name

read -p "Enter another directory name:" dir2

#Check whether the file exists or not using `test`

if test -d $dir2

then

echo "$dir2 directory exists."

else

echo "$dir2 directory does not exist."

fi

Output:

The following output appears after executing the script with the “temp” and “files” directory names. According to the output, both directories exist in the current location. Then, the “ls” command is executed to check the content of the directories:

p8-1

The following output appears after executing the script with the “testing” and “new” directory names. According to the output, both directories do not exist in the current location. Then, the output of the “ls” command shows that both directories don’t exist:

p8-2

Go to top

 

Use of the “If” Statement with Regex

The following script shows the method of validating the input data using an “if” statement with the regex. Here, two input values are taken from the user and are stored in the “$bookname” and “$bookprice” variables. The “if” condition is used in the script to check that the “$bookname” variable contains all alphabetic characters and the “$bookprice” contains a number.

#!/bin/bash

#Take the book name and price from the user

echo -n "Enter the book name:"

read bookname

echo -n "Enter the book price:"

read bookprice

#Check the book name contains the alphabet only

if ! [[ "$bookname" =~ [A-Za-z] ]]; then

echo "Book name is invalid."

else

echo "Book name is valid."

fi

#Check the book price contains digit only

if ! [[ "$bookprice" =~ [0-9] ]]; then

echo "Book price can contain digit only."

else

echo "Book price is valid."

fi

Output:

The following output appears after executing the script with the input values of “Bash Programming” as the book name and 78 as the book price:

p9-1

The following output appears after executing the script with the input values of 90 as the book name and “Bash” as the book price:

p9-2

Go to top

Use of the “Case” Statement

The “case” statement is the alternative of the “if-elif-else” statement but all tasks of the “if-elif-else” statement can’t be done using the “case” statement. The simple use of the “case” statement is shown in the following script. A numeric value is taken from the user as the current month value. Then, the corresponding month is printed if any matching value is found in the “case” statement. Otherwise, the default message is printed.

#!/bin/bash

#Take the current month value in number

read -p "Enter the month of today in number:" b_month

#Print the text before printing the month name

echo -n "The current month name is "

#Find out and print the matching month name based on the input

case $b_month in

1|01) echo "January." ;;

2|02) echo "February." ;;

3|03) echo "March." ;;

4|04) echo "April." ;;

5|05) echo "May." ;;

6|06) echo "June." ;;

7|07) echo "July." ;;

8|08) echo "August." ;;

9|09) echo "September." ;;

10) echo "October." ;;

11) echo "November." ;;

12) echo "December." ;;

*) echo "not found." ;;

esac

Output:

The following output appears after executing the script with the value of 6:

p10-1

The following output appears after executing the script with the value of 09:


p10-2

The following output appears after executing the script with the value of 14:

p10-3

Go to top

Conclusion

Different uses of conditional logic using the “if” and “case” statements are shown in the 10 examples of this tutorial. The concept of using the conditional logic in Bash will be cleared for the new Bash users after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.