Bash Script 6: Loops

Looping in bash is very easy. In the previous posts, there has been a while loop, which was used to process command line arguments. There are 2 other types of loops: for and until. This post will cover all 3 types.

While loops

The while loop will continue to loop until some condition becomes false, or zero. This condition is passed in as a test. Check out the previous post for information on bash tests.

Here’s a simple example:

COUNTER=0
while [ $COUNTER -lt 10 ]
do
  echo $COUNTER
  COUNTER=$((COUNTER + 1))
done

In this example, it loops 10 times, each time echoing the COUNTER then incrementing it. The test could be anything, even checking for the existence of files to process.

Until loops

The until loop is very similar to the while loop, but the condition check is reversed. The loop will continue as long as the condition is false. Here’s the same example as before, but using an until loop:

COUNTER=0
until [ $COUNTER -gt 9 ]
do
  echo $COUNTER
  COUNTER=$((COUNTER + 1))
done

For loops

The for loop iterates over a set of data. I’ve used this for file processing before, because it makes it super easy to do. Here’s an example that will loop through mkv video files in the current folder:

for FILE in ls *.mkv
do
  echo "$FILE";
  #Do Something with $FILE here, perhaps call conv.sh
done