For Your Guidance – Technology

If statement is used to execute the commands based on the conditions. We have different types of if conditions.

Note: we should maintain proper spaces while writing the if statement. otherwise, it will throw an error

Simple If statement

check simple condition 1 equal to 1. If the condition is true then it will execute the echo statement and print the output as true. if the condition is false then it will return nothing.

example:

#check condition 1 is equal to 1
if [ 1 == 1 ]; then
   echo "true"
fi

output: true

If condition with variable

Let’s check the simple if condition using variables instead of hardcode values.
Define a variable named var1 and assign a value of 1. Check if the variable value is 1 then execute the echo command. otherwise, print nothing.

example:

#define variable
var1=1

#check if the variable value is equal to 1
if [ $var1 == 1 ]; then
   echo "var1 value is 1"
fi

output: var1 value is 1

If Else statement

Verify the initial condition, if the condition is true then it will execute the commands within the if block, if the condition fails then commands within that else block will be executed.

Define a variable named var1 with the value 2.

It checks the condition if the var1 value is 1,  if yes then it will print “var1 value is 1”.

otherwise, it executes the commands in the else block and print the output as “var1 value is 2”

example:

#define variable
var1=2
if [ $var1 == 1 ]; then
   echo "var1 value is 1"
else
   echo "var1 value is 2"
fi

output: var1 value is 2

If else if statements

If we want to check multiple conditions sequentially and execute the command whenever the condition is successful, then if else if conditions are useful. If the first condition succeeds then it will execute the commands in the respective condition block. If it fails, then only it will check the next condition and do the same for all the remaining conditions. If any condition is a success then the process will stop checking the other conditions. if all conditions fail then the commands in the else statement will be executed.

example:

#define variable
var1=2
if [ $var1 == 1 ]; then
   echo "value = 1"
elif [ $var1 == 2 ]; then
   echo "value = 2"
else
   echo "value other than 1 or 2"
fi

outptut: value = 2

Nested if statements

This is used to execute conditions inside the other conditions.

As per the below example, it will first check the variable value is less than 10.

if it is true then it will check the inner condition, if the variable value is less than 5 then execute the respective block commands.

example:

#define variable
var1=11
if [ $var1 -lt 10 ]; then
   if [ $var1 -lt 5 ]; then
      echo "var1 value is less than 5"
   else
      echo "var1 value is greather or equal to 5 and less than 10"
   fi
elif [ $var1 -gt 10 ]; then
   echo "var1 value is greathan 10"
else
   echo "var1 value is 10"
fi
5/5
Categories: Linux

Latest Posts