Howard Paget
Projects
About

Bash Looping

May 10, 2022
bash

In this article we’ll loop through some numbers, strings, and lines in a file in Bash!

Structure of a for loop

The basic structure of a for loop in Bash is:

for val in ...
do
  # do something with $val
done

Where ... is a list e.g. {1..10}, 'Tom' 'Dick' 'Harry', less data.txt.

Looping through a sequence of numbers 🔢

It’s surprising common to simply want to run a command multiple times possibly incorporating some counter into the command. This can be achieve with a for loop by looping of a sequence for example {1..10}.

for i in {1..10} # alternatively you could use `seq 1 10`
do
  echo "i is $i"
done

Looping through a list of strings 📃

Instead of looping through a sequence of numbers you may want to loop through a list of strings which can be achieved by replacing the sequence with a list.

for name in 'Tom' 'Dick' 'Harry'
do
  echo "Hello $name"
done

Looping through lines in a file 📁

We have a few options the standard for using less to read a file, a while reading from a file, or xargs reading from the file.

Using for

A for loop can be used to loop through the result of less filename.

for name in `less data.txt`
do
  echo "Hello $name"
done

Using while

A while loop can can be combined with read and input redirection <.

while read p
do
  echo "Item: $p"
done < data.txt

Using xargs

xargs can be used with input redirection < to run a command for each line.

xargs -I {} echo "Item: {}" < data.txt

# or equivalently
xargs -L 1 echo "Item:" < data.txt

Sometimes it’s handy to construct a command as a string and pass to sh.

xargs -I {} sh -c 'echo "Item {}" > "{}.txt"' < data.txt