User Tools

Site Tools


bash:if...then...else

BASH - if...then...else

If takes the form:

if CONDITION 
then
STATEMENTS
fi

NOTE: The statements are only executed if the CONDITION is true.

The fi keyword is used for marking the end of the if statement.


Example

#!/bin/bash
 
echo -n "Enter a number: "
read num
 
if [[ $num -gt 10 ]]
then
echo "Number is greater than 10."
fi

NOTE: The above program will only show the output if the number entered is greater than ten.

The space around the [[ ]] are required!

  • -gt: stands for greater than;

Similarly:

  • -lt: for less than.
  • -le: for less than or equal.
  • -ge: for greater than or equal.

More Control Using If Else

Combining the else construct with if allows much better control over the script’s logic.

#!/bin/bash
 
read n
if [ $n -lt 10 ];
then
echo "It is a one digit number"
else
echo "It is a two digit number"
fi

NOTE: The else part needs to be placed after the action part of if and before fi.


Using Elif

The elif statement stands for 'else if' and offers a convenient means for implementing chain logic.

#!/bin/bash
 
echo -n "Enter a number: "
read num
 
if [[ $num -gt 10 ]]
then
echo "Number is greater than 10."
elif [[ $num -eq 10 ]]
then
echo "Number is equal to 10."
else
echo "Number is less than 10."
fi

AND

Use &&.

#!/bin/bash
 
echo -n "Enter Number:"
read num
 
if [[ ( $num -lt 10 ) && ( $num%2 -eq 0 ) ]]; then
echo "Even Number"
else
echo "Odd Number"
fi

OR

Use ||.

#!/bin/bash
 
echo -n "Enter any number:"
read n
 
if [[ ( $n -eq 15 || $n -eq 45 ) ]]
then
echo "You won"
else
echo "You lost!"
fi

References

See Switch

bash/if...then...else.txt · Last modified: 2021/05/28 09:42 by peter

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki