Unix - Shell Loops

In Unix, shell loops are used to automate repetitive tasks by executing a set of commands repeatedly. There are several types of loops that can be used in Unix shell scripting, but the most commonly used ones are the for loop and the while loop.

For Loop

A for loop is used to iterate over a list of items and perform a set of commands for each item in the list. The basic syntax of a for loop is as follows:

for variable in list

do

   commands

done

Here, the variable is a variable that will hold each item in the list, and the commands will be executed for each item in the list.

For example, the following loop will print the numbers 1 to 5:

for i in 1 2 3 4 5

do

   echo $i

done

 

While Loop

A while loop is used to execute a set of commands repeatedly as long as a certain condition is true. The basic syntax of a while loop is as follows:

while condition

do

   commands

done

Here, the condition is a command that returns a status code. If the status code is zero, the commands will be executed. This will continue until the condition returns a non-zero status code.

For example, the following loop will print the numbers 1 to 5 using a while loop:

i=1

while [ $i -le 5 ]

do

   echo $i

   i=$((i+1))

done

In this loop, the condition is the expression [ $i -le 5 ], which returns a status code of zero as long as i is less than or equal to 5. The commands will be executed until i is greater than 5, at which point the condition will return a non-zero status code and the loop will terminate.

 

Overall, shell loops are a powerful feature in Unix that allow you to automate repetitive tasks and perform complex operations on large data sets.