There might be a scenario where we need a same statement be executed for some 'n' number of times in those cases we usually go for loop commands. We have used these in c,c++,java.The same can be used even in unix shell scripting too
Let's see about some loop commands which can be used in shell scripting. If,For,While,Until.
IF- If keyword followed by condition then set of statements that should be executed upon satisfying the condition and then if loop will be ended with fi keyword
syntax:
if [expression/condition]
then
statements to be executed
fi
eg:
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
fi
for if-else it will be as follows
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
else
echo "a is not equal to b"
fi
For nested if else it should be represented in the following way
#!/bin/sh
a=10
b=20
if [ $a == $b ]
then
echo "a is equal to b"
elif [ $a -gt $b ]
then
echo "a is greater than b"
elif [ $a -lt $b ]
then
echo "a is less than b"
else
echo "None of the condition met"
fi
For : for each variable it will check for condition/values if it is satisfied then set of statements are executed
Syntax:
for var in condn1 condn2 ... condnN
do
Statement(s) to be executed for every condn.
done
eg:
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
Output will be as follows
Welcome 1 times
Welcome 2 times
Welcome 3 times
Welcome 4 times
Welcome 5 times
We will see about more unix loop commands in the coming article
Hope this helps you in understanding unix loop commands
Comments
Post a Comment