Linux Admin - Loops



Like all other programming languages BASH makes use of common looping structures − for, while, and until.

for loop

The for loop is used to execute other shell instructions repeatedly. The for loop is classified as an iteration statement in BASH.

#!/bin/bash 
myFile = "myLines.txt"

for i in `cat $myFile` 
   do 
   echo $i 
done

The above for loop iterates through the contents of *myLines.txt" and echoes each line to the terminal.

Note − When a command is enclosed in backticks (shift+tilde) the command's output will be assigned to a variable.

while loop

This loop will execute until a condition is satisfied. We saw this used previously with the shell routine that repeatedly echoed and incremented.

Let's read a file with the while loop −

#!/bin/bash 
myFile = "myLines.txt"

while read -a FILELINE;  
   do 
   echo $FILELINE 
done < $myFile

Again, this small script displays the contents of our text file.

Note − The first line of your script should always contain the shebang line. This is simply the path to your BASH shell interpreter. Usually, located in /bin/bash on CentOS.

until loop

The until loop is similar in syntax to the while loop. The difference is, the until loop will execute until a command executes successfully.

With that in mind, we'd just need to negate our while script to execute with until

#!/bin/bash 
myFile = "myLines.txt"

until ! read -a FILELINE;
do 
   echo $FILELINE 
done < $myFile 
linux_admin_shell_scripting.htm
Advertisements