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 anif
statement. It checks if the value of the variablecolor
is equal to the string “blue”. The[ "$color" == "blue" ]
part is a conditional expression enclosed within square brackets. The double quotes around$color
ensure that the variable’s value is treated as a single entity.echo "The color is blue."
: If the condition in theif
statement is true (meaning the value ofcolor
is indeed “blue”), this line is executed, and it prints the message “The color is blue.”else
: If the condition in theif
statement is false (meaning the value ofcolor
is not “blue”), the script will skip to this line.echo "The color is not blue."
: In theelse
block, this line is executed, and it prints the message “The color is not blue.”fi
: This keyword marks the end of theif
statement.
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."
fi
This 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=10
andnum2=20
: These lines initialize two variables,num1
with a value of 10 andnum2
with a value of 20.if [ $num1 -eq $num2 ]; then
: This line starts anif
statement. It checks if the value ofnum1
is equal to the value ofnum2
. The-eq
operator is used for numeric equality comparison.echo "The numbers are equal."
: If the condition inside theif
statement is true (meaningnum1
is indeed equal tonum2
), this line is executed, and it prints the message “The numbers are equal.”else
: If the condition inside theif
statement is false (meaningnum1
is not equal tonum2
), the script will skip to this line.echo "The numbers are not equal."
: In theelse
block, this line is executed, and it prints the message “The numbers are not equal.”fi
: This keyword marks the end of theif
statement.
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!"
fi
In 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."
fi
Explanation:
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 variableage
is 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_license
is equal to the string “true”. The double quotes around$has_license
ensure 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."
fi
Explanation:
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 variabletemperature
is greater than 30. If this condition is true, it indicates a hot day.[ "$is_raining" = true ]
: This condition checks if the variableis_raining
is 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
fi
Here’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."
fi
Explanation:
age=20
: This line assigns the value 20 to the variableage
.if [ $age -ge 18 ]; then
: This line starts theif
statement. The condition[ $age -ge 18 ]
checks if the value ofage
is greater than or equal to 18.echo "You are eligible to vote."
: If the condition is true (which it is in this case becauseage
is 20), this line is executed, and it prints the message “You are eligible to vote.”fi
: This keyword marks the end of theif
statement.
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
fi
Here’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."
fi
Explanation:
age=15
: This line assigns the value 15 to the variableage
.if [ $age -ge 18 ]; then
: This line starts theif
statement. The condition[ $age -ge 18 ]
checks if the value ofage
is greater than or equal to 18.echo "You are eligible to vote."
: If the condition in theif
statement 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 theif
statement is false, the script moves to theelif
statement. Here, the condition[ $age -ge 16 ]
checks if the value ofage
is greater than or equal to 16.echo "You can apply for a driving license."
: If theelif
condition is true, this line is executed, and it prints the message “You can apply for a driving license.”else
: If both theif
andelif
conditions are false, the script moves to theelse
block.echo "You are too young for these privileges."
: In theelse
block, 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_false
Explanation:
[ 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."
fi
The 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 theif
statement. It checks whether the value stored in theINPUT_VALUE
variable 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 theif
statement is false, the script moves to theelif
statement. This line checks if the value ofINPUT_VALUE
is greater than or equal to 0 and less than 10.echo "The value is between 0 and 9 (inclusive)."
: If the condition in theelif
statement 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 nextelif
statement. This line checks if the value ofINPUT_VALUE
is greater than or equal to 10 and less than 100.echo "The value is a two-digit number."
: If the condition in the secondelif
statement 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 theelse
block.echo "The value is outside the valid range."
: In theelse
block, this line is executed, and it prints the message “The value is outside the valid range.”fi
: This keyword marks the end of theif
statement.
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
fi
Explanation:
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
if
statement 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
if
statement inside thethen
block checks their response and provides an appropriate message. - If the user is not an adult (age less than 18), the script enters the
else
block and considers them a minor. - For minors, the user is asked whether they are in school. The nested
if
statement inside theelse
block checks their response and provides an appropriate message. - The
elif
statements 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.