Do something every X iteration in a bash loop

If you have a bash loop and want to ”do something” at every X iteration you are in trouble because bash isn’t that good with numbers. Anyway, today I created this small example that you can use. In my case I needed to read a pretty large txt-file and create a simple html output table of the rows. The problem was to insert TR-tags between the TD-tags like below:

td row 1
td row 2
td row 3
tr
td row 4
td row 5
td row 6
tr

My solution solved the problem! It is pretty helpful that we have the modulo (%) operator in bash.

#!/bin/bash

# Change this to how many rows row you want to skip before doing something
doevery=3

for (( c=1; c<=100; c++ ))
do
	remainder=`expr $c % $doevery`
	echo "Remainder: $remainder"

	if [ $remainder = "0" ];	then
		echo "Every $doevery iteration"
		# Do something
	fi

done

Lämna ett svar

E-postadressen publiceras inte. Obligatoriska fält är märkta *

Denna webbplats använder Akismet för att minska skräppost. Lär dig hur din kommentardata bearbetas.