FUNDAMENTALS A Complete Guide for Beginners
Controlling the flow of statements execution in the bash program is a fundamental task of decision-making. Therefore, in the bash script, the if else conditional statement is used to perform the execution of a set of statements by checking the conditions. In this article, I will walk you through a complete guide to the if-else statement including syntax and various examples of it. Moreover, nested if-else is also discussed here. Let’s start the discussion.
Basics of If Statement in Bash
if is a conditional statement that is used to make decisions in the bash script. This statement checks whether the condition is true or false. With an if statement you can set multiple conditions as well.
The basic syntax of the if expression is:
if [condition]; then
# execution code block
fi
if: Starts the if operation.
[condition]: The condition is enclosed with square brackets ‘[ ]’.
then: Separates the condition from the execution code block.
# execution code block: If the condition is true, this code block will be executed.
fi: Ends the if operation.
Basics of If Else Statement in Bash
The if-else is a conditional statement used for conditional branching in bash scripting. When any condition is set using if-else, it will verify the condition. If the condition is true, it will execute the if block statement. When the condition is false, it will execute the else block statement. See the flow diagram of the if-else statement:
The basic syntax of an if-else statement is:
if [ condition ]; then
# execute the code if the condition is true
else
# execute the code if the condition is false
fi
if: Starts the operation.
[condition]: The condition is enclosed with square brackets ‘[ ]’.
then: Separates the condition from the execution code block.
# execute the code if the condition is true: If the condition is true, it will execute this code.
else: Execute another code if the condition is false.
# execute the code if the condition is false: If the condition is false, it will execute this code.
fi: Ends the operation.
Basics of Nested If Else Statements in Bash
Nested if else statements are used to handle complex conditions. It will allow you to explore more precise decision-making by handling multiple conditions.
The basic syntax of the nested if else is:
if [1st condition]; then
# statement1 will be executed if 1st condition is true
if [2nd condition]; then
# statement2 will be executed if both 1st condition and 2nd condition are true
else
# statement3 will be executed if 1st condition is true and 2nd condition is false
fi
else
# statement4 will be executed if 1st condition is false
fi
If the 1st condition is true then the code in the satement1 will be executed. When both conditions are true the statement2 which is nested under the first if statement will be executed. Otherwise, the statement3 will be executed. However, if the first condition is false, the last else block code statement4 will be executed.
Bash If Else Operators
In bash scripting, numerous operators are under the if else statement to perform multiple types of operations. Some of the commonly used operators are provided in the following table:
Operator | Function |
---|---|
-eq | Checks if the integers are equal. |
-ne | Checks if the integers are not equal. |
-gt | Checks if the integer1 is greater than integer2. |
-lt | Checks if the integer1 is less than integer2. |
-ge | Checks if the integer1 is greater than and equal to integer2. |
-le | Checks if the integer1 is less than and equal to integer2. |
= | Checks if the strings are equal. |
!= | Checks if the strings are not equal. |
&& | Multiple commands connected by the AND operator will only execute if all the conditions are true. |
| | | Multiple commands connected by the OR operator will only execute if at least one of the conditions is true. |
-f | Checks if a regular file exists. |
-d | Checks if a directory exists. |
-e | Checks if a file exists. |
-h | Checks if a file exists that is a symbolic link. |
-s | Checks if a non-empty file exists. |
-r | Checks if a file exists that is readable. |
-w | Checks if a file exists that is writable. |
-x | Checks if a file exists that is executable. |
-n | Checks if the length of a variable is greater than zero. |
-z | Checks if a string is null. |
How to Use If Else Statement in Bash
If-else statement can be used to perform different operations over numbers, arguments, strings, and arrays. Moreover, you can use nested if else to operate multiple conditions. Now, I will show you 11 examples of if else statement in the following section. An example of nested if else is also included here.
Example 01: Checking if a Number is Even or Odd With If Else in Bash
Checking a number if it is even or odd is an easy and simple task that helps you understand the function of an if else statement. The following code will show you how to use if else to find an even or odd number:
#!/bin/bash
echo "Enter a number: "
read number
if [ $((number % 2)) -eq 0 ]; then
echo "even number"
else
echo "odd number"
fi
Here, in #!/bin/bash
, ‘#!’ is called shebang or hashbang. It indicates the interpreter to be used for executing the script, in this case, it’s Bash. When you put any number as an input, the read common reads the input number. The % operator divides the input number by 2 and checks if there is any remainder. If it does not find any remainder, the number is even and prints the if code block otherwise the number is odd and prints the else code block. The echo command echoes the quoted message.
In this image, you can see that as an input, number 10 is entered and the output shows it is an even number. When the input number is 11, it shows that this is an odd number.
Example 02: Checking if a Number is Positive, Negative, or Zero With If Else
Whether a number is positive, negative, or zero, can be checked easily using the if-else conditional statement. If a number is greater than zero, it will be a positive number and the number which is less than zero is a negative number.
To check whether a number is positive, negative or zero with an ‘if else statement’, follow the code given below:
#!/bin/bash
echo "Enter a number: "
read number
if [ $number -gt 0 ]; then
echo "It is a positive number."
elif [ $number -lt 0 ]; then
echo "It is a negative number."
else
echo "It is a zero."
fi
In this bash script, if you enter a number, it will verify whether the assigned number is greater than 0 with the -gt
option. If the condition is true it will print “It is a positive number.” Then I set another condition in the elif block that uses the -lt option to check whether the number is less than 0. If the condition is true it will print “It is a negative number.” Finally, it prints the else block code “It is a zero.” if both conditions are false.
Example 03: Nested If Else Statements
Nested if-else statements in Bash are used to create more complex decision-making structures by including multiple levels of conditions. Here’s an example:
#!/bin/bash
echo "Enter a number: "
read num
if [ $num -gt 0 ]; then
echo "positive number."
if [ $((num % 2)) -eq 0 ]; then
echo "even number."
else
echo "odd number."
fi
else
echo "non-positive number."
if [ $num -eq 0 ]; then
echo "it is zero."
else
echo "negative number."
fi
fi
After reading the input number with the read command, it checks whether the number is positive, negative, even, or add. If the number is greater than 0, it prints a “positive number.”. Another statement inside this block checks if the positive number is even or odd. After that, if the number is less than 0, it prints a “non-positive number.”. Another if else statement checks if the number is equal to 0 and prints “it is zero.” otherwise prints “negative number.”.
After running the bash script, you can see a prompt asking you to enter a number. Entering the number 3 displays that it is a positive and an odd number. If you run the bash script again and enter -2, it displays that it’s a non-positive and negative number. Similarly, you can check any number, it will execute the output based on the nested if else conditions.
Example 04: Checking the Number of Arguments With If Else
In the bash script, arguments pass information to the bash script from the command line. Bash offers some special variables like $1, $2, and $3 to pass the first, second, and third argument to the script respectively. The number of arguments is checked by the $# operator.
Now, To know the number of arguments with if else statement, see the bash code given below:
#!/bin/bash
if [ "$#" -eq 0 ]; then
echo "No arguments."
elif [ "$#" -eq 1 ]; then
echo "1 argument."
else
echo "More than 1 argument."
fi
Here, the $#
operator checks the number of arguments provided by the users. When the number of arguments equals 0, it executes if block and shows no arguments. If you put 1 argument, it executes the elif block and displays 1 argument. If you write more than 1 argument, it executes the else block.
The printed output is shown in the picture. In the 1st command, you can see nothing is written after the bash arg.sh script, so it shows no arguments. In the 2nd and 3rd command, ar1 and ar1, ar2 is entered respectively to check the number of arguments provided in the command line. If you enter more than 2 arguments, it displays that there is more than 1 argument.
Example 05: Checking if Creation of a File is Successful With If Else
If you create a file and want to verify whether the task is successful, you can use $? operator in bash within the if else statement. You can also check if the network connection is successful, or the existence of a command using this special operator.
To know whether a file is successfully created or not with if else statement, see the given code below:
#!/bin/bash
echo "Enter the file name: "
read filename
# Attempt to create the file
touch "$filename"
# Check if the file creation was successful
if [ $? -eq 0 ]; then
echo "File '$filename' created successfully."
else
echo "Failed to create the file '$filename'."
fi
A prompt is taken to write a file name according to the users then a touch command is used to create that file. After creating the file, if the $?
is equal to zero, the file is created successfully otherwise fails to be created.
Here, the mou.txt file is created to check if it has been created successfully or not. After running the script and entering the file name, it shows that the file creation is successful.
Example 06: If Else Statement With Logical “AND” Operator in Bash
Generally, the AND operator is used to combine multiple conditions within an if else statement. If all the conditions are true, it will execute the if block output.
The following code will combine two conditions with && operator. See the code below:
#!/bin/bash
echo "Enter your age: "
read age
echo "Do you have a graduation certificate? (yes/no): "
read certificate
if [ "$age" -ge 23 ] && [ "$certificate" = "yes" ]; then
echo "You are eligible to apply for this job."
else
echo "You are not eligible to apply for this job."
fi
Here, 1st prompt is used to enter age and the 2nd one is to take yes or no answer. Within the if condition, two conditions are taken using the &&
operator. If both conditions are true, it displays “You are eligible to apply for this job.” on the other hand, it will print the else block.
Example 07: If Else Statement With Logical “OR” Operator
The OR operator combines multiple conditions but it does not need to satisfy all the conditions like the AND operator. If only one condition is true, the output will be executed. Here, I will explain the same example used in the previous AND section to let you how the || operator works under the if else statement. Check the code mentioned below:
#!/bin/bash
echo "Enter your age: "
read age
echo "Do you have a graduation certificate? (yes/no): "
read certificate
if [ "$age" -ge 23 ] || [ "$certificate" = "yes" ]; then
echo "You are eligible to apply for this job."
else
echo "You are not eligible to apply for this job."
fi
Unlike the AND operator, the OR operator does not need to satisfy both conditions. From the two conditions, if at least one condition whether age or the certificate is true, the output will show the if block code “You are eligible to apply for this job.” otherwise, it will execute the else block code “You are not eligible to apply for this job.”.
You can see the bash OR.sh script’s output in this image. After entering the age of 24 and answering ‘no’ to the 2nd question, it still executes the code that you are eligible to apply for this job. This is how the OR operator works with if else statement.
Example 08: Concatenating Strings With If Else in Bash
Concatenating strings is one of the common tasks that everyone should learn to operate the bash script. You are going to have more control over the concatenation of the strings by adding the if else condition with it.
This example will explain how to add two strings using the if else statement. Follow the script provided below:
#!/bin/bash
echo "Enter your name: "
read name
string2="welcome to linuxsimply.com"
if [ "$name" = "john" ]; then
string1="john"
else
string1="$name"
fi
echo "$string1 $string2"
If you write the name john, it will add this string1 with the string2="welcome to linuxsimply.com"
. Else you write another name, that will also be added with string2.
Here, the 1st string is ‘name’ and the 2nd string is ‘welcome to linuxsimply.com’. If you write the name john, the output will be ‘john welcome to linuxsimply.com’ and if put another name, it will add the name with the 2nd string and print the output.
Example 09: Arithmetic Operation With Variables Using If Else
Arithmetic operations mean addition, subtraction, multiplication, and division of variables. These operations can be performed based on different conditions using the if else statement.
Here, the addition operation is explained. You can perform other operations as well following a similar procedure. Check the example below:
#!/bin/bash
echo "Enter number1: "
read num1
echo "Enter number2: "
read num2
sum=$((num1 + num2))
if [ $sum -gt 50 ]; then
echo "$sum is greater than 50."
else
echo "$sum is less than 50."
fi
Here, the addition operation is performed by adding number1 and number2. If the sum of the two numbers is greater than 50, it will execute the if block code. If it is false, it will execute the else block code.
Two input variables 30 and 40 are taken to calculate the sum and a condition is set using the if else statement. You can notice that the sum of the variables is 70 that’s why it shows the sum is greater than 50. Then as an input variables 20 and 20 are added and it shows that the sum is less than 50.
Example 10: Checking If a File Exists With If Else
You can check whether a file exists in your Ubuntu or not using the if else condition. Here, the -e option is used to check the file’s existence. You can also check if a directory exists using the if else statement.
Follow the script provided below to check file existence:
#!/bin/bash
filepath="/home/mou/file1.txt"
# Check if the file exists
if [ -e "$filepath" ]; then
echo "The file1.txt exists."
else
echo "The file1.txt does not exist."
fi
A file path is defined as /home/mou/file1.txt
to check the file1.txt exists in the /home/mou
location. Within the if else condition, file existence is checked using the -e flag.
You can see in this image that the file1.txt exists in the specified location.
Example 11: Using If Else to Verify Password in Bash
Verifying passwords is a common practice to avoid unauthorized access. Using the if else condition, you can check if the password is correct or wrong. You will get only access if the password matches with the specified password.
To know the process of verifying password using if else statement, follow the below code:
#!/bin/bash
# Define the valid password
valid_pass="secret"
echo "Enter your password: "
read entered_pass
# Check if the entered password is correct
if [ "$entered_pass" == "$valid_pass" ]; then
echo "valid password, access granted."
else
echo "invalid password."
fi
First of all, you have to define a valid password which is ‘secret’. After writing a password in the prompt, it verifies if the entered password==valid password. If both password matches, that is a valid password otherwise the password is invalid.
In this picture, you can notice that when you write the specified password ‘secret’, it shows that it is a valid password and you get access. However, if you write another password ‘mou’, it shows that the password is invalid.
Conclusion
I hope this article helps you understand the uses of if else condition. Here, I have shown the basics of the if else statement including examples and various important operators used on a regular basis within the if else condition. In addition, 11 examples are explained to let you know the different uses of this conditional statement. Follow each step properly to get an accurate output. Best wishes.
People Also Ask
What is the else if statement in Bash?
In Bash, the elif statement is used to check multiple conditions sequentially, acting as a combination of “else” and “if” in other programming languages. It allows the script to evaluate and execute the block of code associated with the first true condition encountered. If none of the conditions is true, the else block is executed.
Is an if-else statement a function?
No, an if-else statement is not a function. In programming, an if-else statement is a control structure used for decision-making. It allows the execution of different code blocks based on whether a specified condition evaluates to true or false. It is a fundamental part of the flow control in many programming languages, including Bash.
Is there Elif in bash?
Yes definitely, there is an elif in bash which basically means else if. It is used for complex conditional operations.
What does @$ mean in bash?
This special operation passes all the command line arguments to the bash script and it must be written within double quotes “@$”.
What does == mean in bash?
The == is used to compare strings in bash. For example, string1==string2 condition will be true if both strings are equal.
Related Articles
- Check If a Variable Exists in Bash If Statement
- Check If An Input Argument Exists in Bash [4 Methods]
- Check If a String Contains Substring, Number & Letter in Bash
- Check If a String is Empty or Not in Bash [5 Methods]
- How to Compare Strings in Bash With if Statement [6 Methods]
- How to Compare Numbers in Bash With If Statement [2 Methods]
- Check If Array Contains an Element in Bash [6 Methods]
- Bash if-else Condition in One-Line [2 Ways]
- Using grep in if Statement in Bash [4 Cases]
- How to Use Regex in Bash If Condition? [4 Cases]
- Bash rm If Exists [All Case Explained]
- What is ‘$?’ in the Bash if Statement? [8 Examples]
<< Go Back to Bash Conditional Statements | Bash Scripting Tutorial