DEV Community

Mahbub Ferdous Bijoy
Mahbub Ferdous Bijoy

Posted on

Shell -If/elif/else and loops

Numeric Comparison logical operators:

Comparison is used to check if statements evaluate to true or false. We can use the below shown operators to compare two statements:

  1. Equality :num1 -eq num2 --------> is num1 equal to num2
  2. Greater than equal to:num1 -ge num2 --------> is num1 greater than equal to num2
  3. Greater than :num1 -gt num2 --------> is num1 greater than num2
  4. Less than equal to :num1 -le num2 --------> is num1 less than equal to num2
  5. Less than :num1 -lt num2 --------> is num1 less than num2
  6. Not Equal to :num1 -ne num2 --------> is num1 not equal to num2

if code structure:

if [ conditions ]
    then
         commands
fi
Enter fullscreen mode Exit fullscreen mode

if else code structure:

if [[ condition ]]
then
    statement
elif [[ condition ]]; then
    statement 
fi
Enter fullscreen mode Exit fullscreen mode

if elif else code structure:

if [[ condition ]]
then
    statement
elif [[ condition ]]; then
    statement 
else
    statement
fi
Enter fullscreen mode Exit fullscreen mode

we can use AND -a and OR -o as well.

Example:

#! /bin/bash

read a
read b
read c


# if statement :

if [$a -e $b]
than
    echo a is equal to b
elif [$a -gt $b]
    than
    echo a is greater than b
else [$a -lt $b]
    than
    echo a is less than b
fi 



# we can use AND (-a) and OR (-o) as well.

if [$a -ne $b -o $a -e $b]
    than 
        echo "true"
    elif [$a -gt $b -a $b -ge $c]
        than 
            echo "elif true"
        else
            than
                echo "false"
fi


Enter fullscreen mode Exit fullscreen mode

shell script for...while loops:

#! /bin/bash

# For loops allow you to execute statements a specific number of times:

for i in 0 1 2 3 4 5 6 7 8 9 
    do
        echo $i
done

# for loop for os file system :


for FILE in $HOME/.bash*
do
   echo $FILE
done

# for loop for strings :

for X in cyan magenta yellow  
do
    echo $X
done

# while loop :

i=1
while [[ $i -le 10 ]] ; do
   echo "$i"
  (( i += 1 ))
done

Enter fullscreen mode Exit fullscreen mode

Top comments (0)