Example 1: If Statement to compare string
color="blue"
if [ "$color" == "blue" ]; then
echo "The color is blue."
else
echo "The color is not blue."
fi
This Bash code is a simple example of an if statement that checks the value of the variable color and prints a message based on its value. Here’s the breakdown:
color="blue": This line assigns the value “blue” to the variable namedcolor.if [ "$color" == "blue" ]; then: This line initiates anifstatement. It checks if the value of the variablecoloris equal to the string “blue”. The[ "$color" == "blue" ]part is a conditional expression enclosed within square brackets. The double quotes around$colorensure that the variable’s value is treated as a single entity.echo "The color is blue.": If the condition in theifstatement is true (meaning the value ofcoloris indeed “blue”), this line is executed, and it prints the message “The color is blue.”else: If the condition in theifstatement is false (meaning the value ofcoloris not “blue”), the script will skip to this line.echo "The color is not blue.": In theelseblock, this line is executed, and it prints the message “The color is not blue.”fi: This keyword marks the end of theifstatement.
So, the purpose of this code is to check if the value of the color variable is “blue” and then print a corresponding message. If the value is “blue”, it outputs “The color is blue.” If the value is anything other than “blue”, it outputs “The color is not blue.”
Output:
rahil@WorkPC:~/scripts$ touch example1.sh
rahil@WorkPC:~/scripts$ vi example1.sh # Copy and paste above code
rahil@WorkPC:~/scripts$ chmod 755 example1.sh
rahil@WorkPC:~/scripts$ bash example1.sh
The color is blue.
rahil@WorkPC:~/scripts$
Example 2: If statement to compare numbers.
#!/bin/bash
num1=10
num2=20
if [ $num1 -eq $num2 ]; then
echo "The numbers are equal."
else
echo "The numbers are not equal."
fiThis Bash code demonstrates an if statement that compares two numeric variables, num1 and num2, and prints a message based on whether they are equal. Let’s break it down step by step:
num1=10andnum2=20: These lines initialize two variables,num1with a value of 10 andnum2with a value of 20.if [ $num1 -eq $num2 ]; then: This line starts anifstatement. It checks if the value ofnum1is equal to the value ofnum2. The-eqoperator is used for numeric equality comparison.echo "The numbers are equal.": If the condition inside theifstatement is true (meaningnum1is indeed equal tonum2), this line is executed, and it prints the message “The numbers are equal.”else: If the condition inside theifstatement is false (meaningnum1is not equal tonum2), the script will skip to this line.echo "The numbers are not equal.": In theelseblock, this line is executed, and it prints the message “The numbers are not equal.”fi: This keyword marks the end of theifstatement.
So, when you run the script, it will compare the values of num1 and num2 (which are 10 and 20, respectively). Since they are not equal, the script will output “The numbers are not equal.”
Example 3: if statement on less than an x number
#!/bin/bash
score=85
passing_score=70
if [ $score -lt $passing_score ]; then
echo "You did not pass."
else
echo "Congratulations, you passed!"
fiIn this example, the -lt operator is used to check if the value of the variable score is less than the value of passing_score. If score is indeed less than passing_score, the script will output “You did not pass.” Otherwise, it will output “Congratulations, you passed!”
Example 4: If statement with logical AND operator
Here’s an example of an if statement in Bash that uses the logical AND (&&) operator to combine two conditions:
#!/bin/bash
age=25
has_license=true
if [ $age -ge 18 ] && [ "$has_license" = true ]; then
echo "You are eligible to drive."
else
echo "You are not eligible to drive."
fiExplanation:
In this example, the script checks two conditions using the logical AND (&&) operator within the if statement:
[ $age -ge 18 ]: This condition checks if the variableageis greater than or equal to 18. If this condition is true, it means the person is of legal driving age.[ "$has_license" = true ]: This condition checks if the variablehas_licenseis equal to the string “true”. The double quotes around$has_licenseensure that the value is treated as a single entity.
The logical AND operator && combines these conditions. The if statement evaluates whether both conditions are true. If both conditions are true, the script will output “You are eligible to drive.” If either of the conditions is false, it will output “You are not eligible to drive.”
Using the logical AND operator in this manner allows you to make decisions based on multiple conditions, ensuring that both conditions must be true for the if block to execute.
Example 5: If statement with logical OR operator
Here’s an example of an if statement in Bash that uses the logical OR (||) operator to combine two conditions:
#!/bin/bash
temperature=28
is_raining=true
if [ $temperature -gt 30 ] || [ "$is_raining" = true ]; then
echo "It's a good day to stay indoors."
else
echo "It's a nice day to go outside."
fiExplanation:
In this example, the script checks two conditions using the logical OR (||) operator within the if statement:
[ $temperature -gt 30 ]: This condition checks if the variabletemperatureis greater than 30. If this condition is true, it indicates a hot day.[ "$is_raining" = true ]: This condition checks if the variableis_rainingis equal to the string “true”.
The logical OR operator || combines these conditions. The if statement evaluates whether either of the conditions is true. If either condition is true (i.e., it’s either a hot day or it’s raining), the script will output “It’s a good day to stay indoors.” If both conditions are false, it will output “It’s a nice day to go outside.”
Using the logical OR operator in this manner allows you to make decisions based on multiple conditions, ensuring that at least one of the conditions must be true for the if block to execute.
Example 6: If then statement
The if statement in Bash is used for conditional execution. It allows you to specify a condition, and if that condition evaluates to true, a certain block of code is executed. Here’s the basic syntax of an if statement:
if [ condition ]; then
# Code to be executed if the condition is true
fiHere’s an example to help you understand how the if statement works:
#!/bin/bash
age=20
if [ $age -ge 18 ]; then
echo "You are eligible to vote."
fiExplanation:
age=20: This line assigns the value 20 to the variableage.if [ $age -ge 18 ]; then: This line starts theifstatement. The condition[ $age -ge 18 ]checks if the value ofageis greater than or equal to 18.echo "You are eligible to vote.": If the condition is true (which it is in this case becauseageis 20), this line is executed, and it prints the message “You are eligible to vote.”fi: This keyword marks the end of theifstatement.
In this example, the if statement checks whether the value of the age variable is greater than or equal to 18. Since 20 is indeed greater than 18, the condition is true, and the message “You are eligible to vote.” is printed to the console. If the condition were false, the message would not be printed.
Example 7: Elif statement
The elif statement in Bash is used to add an additional condition to the if statement. If the initial if condition is false, the script checks the elif condition. If the elif condition is true, a different block of code is executed. Here’s the basic syntax of an if statement with elif:
if [ condition1 ]; then
# Code to be executed if condition1 is true
elif [ condition2 ]; then
# Code to be executed if condition2 is true
else
# Code to be executed if both condition1 and condition2 are false
fiHere’s an example to help you understand how the elif statement works:
#!/bin/bash
age=15
if [ $age -ge 18 ]; then
echo "You are eligible to vote."
elif [ $age -ge 16 ]; then
echo "You can apply for a driving license."
else
echo "You are too young for these privileges."
fiExplanation:
age=15: This line assigns the value 15 to the variableage.if [ $age -ge 18 ]; then: This line starts theifstatement. The condition[ $age -ge 18 ]checks if the value ofageis greater than or equal to 18.echo "You are eligible to vote.": If the condition in theifstatement is true, this line is executed, and it prints the message “You are eligible to vote.”elif [ $age -ge 16 ]; then: If the condition in theifstatement is false, the script moves to theelifstatement. Here, the condition[ $age -ge 16 ]checks if the value ofageis greater than or equal to 16.echo "You can apply for a driving license.": If theelifcondition is true, this line is executed, and it prints the message “You can apply for a driving license.”else: If both theifandelifconditions are false, the script moves to theelseblock.echo "You are too young for these privileges.": In theelseblock, this line is executed, and it prints the message “You are too young for these privileges.”
In this example, the script checks different age-related conditions using the if, elif, and else statements, and it prints appropriate messages based on the age provided.
Example 8: Shorthand version of if-else
Certainly! In Bash, you can use a shorthand version of the if statement when you have a single command to execute based on a condition. This is often called the ternary operator. Here’s the syntax:
[ condition ] && command_if_true || command_if_falseExplanation:
[ condition ]: This is the condition you want to check. It can be any valid shell expression.&&: This is the logical AND operator. If the condition is true, the command following it will be executed.command_if_true: This is the command that will be executed if the condition is true.||: This is the logical OR operator. If the condition is false, the command following it will be executed.command_if_false: This is the command that will be executed if the condition is false.
Here’s an example:
#!/bin/bash
age=20
[ $age -ge 18 ] && echo "You are eligible to vote." || echo "You are not eligible to vote."Explanation:
In this example, the script checks whether the value of the age variable is greater than or equal to 18. If the condition is true, it executes the command echo "You are eligible to vote.". If the condition is false, it executes the command echo "You are not eligible to vote.".
This shorthand version of the if statement can be useful for simple conditional actions that involve executing a single command based on the condition’s outcome.
Example 9: If-elif, else-if with user numeric input example
#!/bin/bash
read -p "Please enter a value: " INPUT_VALUE
if [[ $INPUT_VALUE -lt 0 ]]; then
echo "Negative value provided."
elif [[ $INPUT_VALUE -ge 0 && $INPUT_VALUE -lt 10 ]]; then
echo "The value is between 0 and 9 (inclusive)."
elif [[ $INPUT_VALUE -ge 10 && $INPUT_VALUE -lt 100 ]]; then
echo "The value is a two-digit number."
else
echo "The value is outside the valid range."
fiThe provided Bash code is an example of a script that takes user input and uses conditional statements to determine characteristics of the input value. Here’s a detailed explanation of each part of the code:
#!/bin/bash: This is called a shebang and indicates that the script should be interpreted using the Bash shell.read -p "Please enter a value: " INPUT_VALUE: This line prompts the user to input a value and assigns the input to the variableINPUT_VALUE.if [[ $INPUT_VALUE -lt 0 ]]; then: This is the start of theifstatement. It checks whether the value stored in theINPUT_VALUEvariable is less than 0.echo "Negative value provided.": If the condition in the previous line is true (meaning the input value is negative), this line is executed, and it prints the message “Negative value provided.”elif [[ $INPUT_VALUE -ge 0 && $INPUT_VALUE -lt 10 ]]; then: If the condition in theifstatement is false, the script moves to theelifstatement. This line checks if the value ofINPUT_VALUEis greater than or equal to 0 and less than 10.echo "The value is between 0 and 9 (inclusive).": If the condition in theelifstatement is true (meaning the input value is between 0 and 9), this line is executed, and it prints the message “The value is between 0 and 9 (inclusive).”elif [[ $INPUT_VALUE -ge 10 && $INPUT_VALUE -lt 100 ]]; then: If the second condition is false, the script moves to the nextelifstatement. This line checks if the value ofINPUT_VALUEis greater than or equal to 10 and less than 100.echo "The value is a two-digit number.": If the condition in the secondelifstatement is true (meaning the input value is a two-digit number), this line is executed, and it prints the message “The value is a two-digit number.”else: If none of the conditions above are true, the script reaches theelseblock.echo "The value is outside the valid range.": In theelseblock, this line is executed, and it prints the message “The value is outside the valid range.”fi: This keyword marks the end of theifstatement.
This script takes user input, checks its value against different conditions, and provides output messages accordingly. It showcases the use of if, elif, and else statements to perform conditional branching based on the value of the INPUT_VALUE variable.
Example 10: if-else-then-elfi advance programming example
Here’s an advanced example of using nested if, else, then, and elif statements in Bash programming:
#!/bin/bash
read -p "Enter your age: " age
if [ $age -ge 18 ]; then
echo "You are an adult."
read -p "Do you have a driver's license? (yes/no): " has_license
if [ "$has_license" = "yes" ]; then
echo "You can drive."
elif [ "$has_license" = "no" ]; then
echo "You cannot drive."
else
echo "Invalid input for license status."
fi
else
echo "You are a minor."
read -p "Are you in school? (yes/no): " is_in_school
if [ "$is_in_school" = "yes" ]; then
echo "You are a student."
elif [ "$is_in_school" = "no" ]; then
echo "You are not a student."
else
echo "Invalid input for school status."
fi
fiExplanation:
In this advanced example, the script takes user input for their age and then uses nested if and else statements to gather more information based on the age category. Here’s how it works:
- The user is prompted to enter their age.
- The outer
ifstatement checks if the age is greater than or equal to 18. If true, it means the user is an adult. - If the user is an adult, they are asked whether they have a driver’s license. The nested
ifstatement inside thethenblock checks their response and provides an appropriate message. - If the user is not an adult (age less than 18), the script enters the
elseblock and considers them a minor. - For minors, the user is asked whether they are in school. The nested
ifstatement inside theelseblock checks their response and provides an appropriate message. - The
elifstatements handle cases where the user provides unexpected input (“yes” or “no” responses are expected).
This example showcases how to use nested if, else, then, and elif statements to create more complex decision-making structures based on user input and different conditions.


