Bash if loop examples (if then fi, if then elif fi, if then else fi)

The if Statement

The if statement allows you to specify courses of action to be taken in a shell script, depending on the success or failure of some command. It is a conditional statement that allows a test before performing another statement. The syntax for the simplest form is:

if [ condition ] 
then
 block_of_statements
fi

Here,

  • The condition in the if statement often involves a numerical or string test comparison, but it can also be any command that returns a status of 0 when it succeeds and some nonzero status when it fails.
  • The statements that follow the then statement can be any valid UNIX command, any executable user program, any executable shell script, or any shell statement with the exception of fi.
  • End every if statement with the fi statement.

Numeric and String Comparison

You can compare number and string in a bash script and have a conditional if loop based on it. The following example sets a variable and tests the value of the variable using the if statement. The then statement is placed on the same line with the if.

#!/bin/bash
age=21
if [ $age -gt 18 ]
then
  echo "You are old enough to drive in most places."
fi

Below are some of the most commonly used numeric comparisons.

Numeric Comparison Returns true (0) if:
[ $num1 -eq $num2 ] num1 equals num2
[ $num1 -ne $num2 ] num1 does not equal num2
[ $num1 -lt $num2 ] num1 is less than num2
[ $num1 -gt $num2 ] num1 is greater than num2
[ $num1 -le $num2 ] num1 is less than or equal to num2
[ $num1 -ge $num2 ] num1 is greater than or equal to num2

Similar to numeric comparison, you can also compare string in an if loop. In below example, a varibale value is set as a string and further compared in the if loop with string “fred”.

#!/bin/bash
name=John
if [ $name = "John" ]
then
  echo "John is here !!!"
fi

Below are the most commonly used string comparisons.

String Comparison Returns true (0) if:
[ str1 = str2 ] str1 equals str2
[ str1 != str2 ] str1 does not equal str2
[ str1 str1 precedes str2 in lexical order
[ str1 > str2 ] str1 follows str2 in lexical order
[ -z str1 ] str1 has length zero (holds null value)
[ -nstr1 ] str1has nonzero length (contains one or more characters)
Note – Lexical order means that lowercase letters have greater value than uppercase letters. As such, attempting to compare mixed-case strings might produce unexpected results.

if then else statement

In a conditional, you frequently have tasks to perform when the tested condition succeeds or fails. The shell can accommodate this with the if/then/else syntax. In the if/then/else form of the if statement, the block of statements after the then statement is executed if the condition succeeds. Execution continues with the statement following the fi statement. If the condition in the if statement fails, then the block of statements after the then statement is skipped, and statements following the else are executed. Execution continues with the statement following the fi statement. The syntax for if/then/else is:

if [ condition ] 
then
 block_of_statements
else
 block_of_statements
fi

Below is an simple example of if else loop using string comparison. It will check if the varibale “total” has a value assigned equal to 100.

#!/bin/bash
total=100
if [ $total -eq 100 ]; then
 echo "total is equal to 100"
else
 echo "total is not equal to 100"
fi

if/then/elif/else statement

In the if/then/elif/else form of the if statement, the first else becomes another if statement or “elif” instead of a simple else. The shell first evaluates condition 1, then condition 2, and so on, stopping with the first condition that succeeds. The statements associated with that successful condition are then executed, followed by any statements after the fi statement. If none of the condition succeeds, then the statements following the else statement are executed. Execution then continues with any statements following the fi statement. The syntax for if/then/elif/else is:

if [ condition 1 ]  
then
 block_of_statements 
elif [ condition 2 ] 
then
 block_of_statements
else 
 block_of_statements
fi

Below is an example of if/then/elif/else form of the if loop statement.

!/bin/bash
total=100
if [ $total -eq 100 ]
then
 echo "total is equal to 100"
elif [ $total -lt 100 ]
then
 echo "total is less than 100"
else
 echo "total is greater than 100"
fi
Note – The if/then/elif/else syntax can have as many elif command statements as needed before the final else statement. Follow each elif by a then statement.

Below is an example of elif Ladder Statements.

#!/bin/bash

name=snoopy

if [ "$name" = "snoopy" ] then
 echo "It was a dark and stormy night."
elif [ "$name" == "charlie" ]
then
 echo "You’re a good man Charlie Brown."
elif [ "$name" == "lucy" ]
then
 echo "The doctor is in."
elif [ "$name" == "schroeder" ]
then
 echo "In concert." 
else
 echo "Not a Snoopy character."
fi

Nested if Statements

You can use an if statement inside another if statement (it’s ok to have nested if statements). You can have as many levels of nested if statements as you can track. In the following example:
1. You input the year as a command-line argument.
2. The script assigns the value of $1 to the year variable.
3. The rest of the script determines if the year entered is a leap year and prints an appropriate message if it is.

The second if statement contains an if statement as one of its statements, which is where the nesting occurs. For the script to print that the year as a leap year:
1. The condition that the year entered be evenly divisible by 4 must be true.
2. The condition that the year not be evenly divisible by 100 must also be true.

#!/bin/bash

if [ $# -ne 1 ] 
then
 echo "You need to enter the year."
 exit 1 
fi

year=$1

if [ $[$year % 400] -eq "0" ]
then
 echo "$year is a leap year!" 
elif [ $[$year % 4] -eq 0 ]
then
 if [ $[$year % 100] -ne 0 ]
 then
  echo "$year is a leap year!"
 else
  echo "$year is not a leap year."
 fi
else
 echo "$year is not a leap year."
fi

Multiple conditions in if loop (Boolean Operators)

Another really useful example of if loops is to have multiple conditions being tested in a single if statement. We can use Boolean Opertors such as OR (||), AND (&&) to specify multiple conditions. Below is an example of specifing an “AND” condition in if loop condition.

#!/bin/bash
num=150
if [ $num -gt 100 ] && [ $num -lt 200 ]
then
 echo "The number lies between 100 and 200"
fi
Related Post