top of page

Linux If-Then-Else Statement

If-then-else statements in Linux allows you to define conditions. Based on conditions you can make program execute specific commands.


If-then-else


The basic syntax for if-then-else condition in Linux is

if [ <test-condition> ]; then
    <statements>
fi

The if statement is followed by a test condition. If the condition is TRUE, the statements get executed. If the condition is FALSE, the entire IF block is ignored. Consider

#!/bin/bash

read -p "Enter a number: " num

if [ $num -lt 10 ]; then
    echo "Number entered is less than 10."
fi

The above script will only work if the number entered by user is less than 10 (condition is TRUE). If the number entered by user is above 10 (condition is FALSE), entire IF block is ignored.


To handle the FALSE condition, we use IF-THEN-ELSE block. Consider below script

#!/bin/bash

read -p "Enter a number: " num

if [ $num -lt 10 ]; then
    echo "Number entered is less than 10."
else
    echo "Number entered is greater than 10."
fi

If the user inputs a number below 10, the first echo command is executed. If the value entered is anything else, the ELSE part is executed.



IF-THEN-ELIF


Sometimes you would want to test a condition within a condition. Consider below script

#!/bin/bash

read -p "Enter a number: " num

if [ $num -lt 10 ]; then
    echo "Number entered is less than 10."
elif [ $num -eq 20 ]; then
    echo "Number entered is 20."
else
    echo "Number entered is greater than 20."
fi

The above script is testing if number entered by user is less than 10. If not, then its checking if number entered is equals to 20. If not, then we have final ELSE block to print for any other value entered by user.



Conditional Operators


Here are some of the commonly used conditional operators to test conditions

  • STRING1 = STRING2: TRUE if both strings are equal

  • STRING1 != STRING2: TRUE if both strings are not equal

  • NUMBER1 -eq NUMBER2: TRUE if both numbers are equal

  • NUMBER1 -lt NUMBER2: TRUE if number 1 is less than number 2

  • NUMBER1 -gt NUMBER2: TRUE if number 1 is greater than number 2

  • NUMBER1 -le NUMBER2: TRUE if number 1 less than or equal to number 2

  • NUMBER1 -ge NUMBER2: TRUE if number 1 greater than or equal to number 2

🍄🍄🍄

Related Posts

Heading 2

Add paragraph text. Click “Edit Text” to customize this theme across your site. You can update and reuse text themes.

bottom of page