Bash Conditional

Bash Conditional Statements are used to execute a block of statements based on the result of a condition.

Bash Conditional Statement Tutorials

The following tutorials cover conditional statements in Bash with detailed explanation and examples.

ADVERTISEMENT

Examples

The following examples demonstrate how to use if, if-else, elif, and case statements in bash scripting.

Bash If

In the following script, we conditionally execute if-block statement(s) based on the condition: if value of x is 5. Since we have take x as 5, the condition becomes true and the if-block executes.

Example.sh

x=5

if [ $x == 5 ];
then
    echo "Value of x is 5."
fi

Output

Value of x is 5.

Bash If-Else

In the following script, we conditionally execute if-block statement(s) or else-block statement(s) based on the condition: if value of x is 5. Since we have take x as 4, the condition becomes false and the else-block executes.

Example.sh

x=4

if [ $x == 5 ];
then
    echo "Value of x is 5."
else
    echo "Value of x is not 5."
fi

Output

Value of x is not 5.

Bash Elif

In the following script, we have an elif statement with multiple conditions. While evaluating from top to bottom, when the condition becomes true, the corresponding block of statement(s) execute. If none of the condition is true, else block executes, if there is else block provided.

Example.sh

x=2
 
if [ $x -eq 1 ]; then
    echo "Value of x is 1."
elif [ $x -eq 2 ]; then
    echo "Value of x is 2."
else
    echo "Value of x is other than 1 and 2."
fi

Output

Value of x is 2.

Bash Case

In the following script, we used case statement. Based on the value of x, the matching block executes. Since we have take 12 in x, the block corresponding to the value 12) executes.

Example.sh

x=12
 
# if condition is true
case $x in
9)
    echo Good Morning!
    ;;
12)
    echo Good Noon!
    ;;
17)
    echo Good Evening!
    ;;
21)
    echo Good Night!
    ;;
esac

Output

Good Noon!

Examples Based on If Statement

Examples Based on If Else Statement

Examples Based on Elif Statement

Conclusion

In this Bash Tutorial, we learned about different conditional statements available in Bash scripting, examples for each of these statements, and some more examples covering scenarios where these conditional statements are used.