Looping statements in BASH shell scripting

We can use below looping statements in Linux shell scripting.

  1. while
  2. for

while loop

while <condition>
do
statements….
done

Here is an example on while loop. Below loop will print values from 1 to 10.
count=1

while [ “$count” -le 10 ]
do
echo $count

# let “count += 1”
((count = count + 1))
done

for loop

Here are some of the examples on for loop.

for i in 1 2 3 4 5
do
echo “value of i is $i”
done

for i in {1..3}
do
echo “value of i is $i”
done

for (( i=1; i<=3; i++ ))
do
echo “Value of i -> $i”
done

Below code will kill all process that match pattern – “myPattern”

for KILLPID in `ps ax | grep ‘myPattern’ | awk ‘ { print $1;}’`; do
kill -9 $KILLPID;
done

for KILLPID in `pgrep anyprocessname`; do
kill -9 $KILLPID;
done

You may also like...