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
td row 4
td row 5
td row 6

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


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

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

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


Lämna ett svar

Din e-postadress kommer inte publiceras. Obligatoriska fält är märkta *

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