Interview Questions

Shell Script – IF Loop

The IF condition is used to take decision in scripting i.e., used to execute blocks of code based on the given condition which evaluates to true or false.

Syntax

If condition
then
        //command X executes when condition is true
else
        //command Y executes when condition is false
fi

If loop – Using Integer comparison

#!/bin/sh
x=1

if [ $x -eq 1 ]
then
        echo "value of x is 1"
fi

If - else - if loop – Using String comparison

 #!/bin/sh
name=test

if [ $name == "test" ]
then
        echo "Name is test"
elif [ $name == "test1" ]
then
        echo "Name is test1"
else
        echo "Name is $name"
fi

If loop – Using test command
Test command is used to check whether the given expression is true or false.

#!/bin/sh
x=10

if test $x > 5
then
        echo "Input Value is greater than 5"
else
        echo "Input Value is lesser than 5"
fi