How to use loop operator in shell scripting

How to use loop operator in shell scripting


In this article, we will learn that how to shell loop control in Unix. So far you have looked at creating loops and working with loops to accomplish different tasks. Sometimes you need to stop a loop or skip iterations of the loop.



In this chapter, we will learn the following two statements that are used to control shell loops−

The break statement

The continue statement

The Infinite Loop:

All the loops have a limited life and they come out once the condition is false or true depending on the loop.





A loop may continue forever if the required condition is not met. A loop that executes forever without terminating executes for an infinite number of times. For this reason, such loops are called infinite loops.

#! /bin/bash

#break and continue

#Break

for (( i=1; i<=10; i++ ))
do
     if [ $i -gt 5 ]
then
     break
fi
     echo "$i"
done

#continue




for (( i=1; i<=10; i++ ))
do
   if [ $i -eq 5 ]
then
    continue
fi
    echo "$i"
done

Example:

for (( i=1; i<=10; i++ ))
do
    if [ $i -eq 5 -o $i -eq 9 ]
then
     continue
fi
      echo "$i"
done

Share:

0 comments

Please leave your comments...... Thanks