Linux shell scripts: How to increment a counter in a shell script

Unix/Linux shell script FAQ: Can you share a simple Linux shell script that shows how to count, i.e., a shell script that increments a counter in a for loop or while loop?

Sure, I just needed to increment a while loop counter myself, so I thought I'd share my example shell script code here.

Using a counter in a Linux shell script while loop

In my case, I just needed to create 200 redirect statements for an Apache config file, as I just reformatted some Java and object oriented programming training class material, and I wanted to make sure anyone looking for the old filenames would still find the tutorial. To do this, I created 200 "Redirect" statements in a shell script loop, redirected that output to a file, then imported those lines into my Apache configuration file.

Here's the source code for this "shell script loop counter" example:

#
# a shell script loop/counter example
# alvin alexander, http://alvinalexander.com
#
count=1
while [ $count -lt 200 ]
do
  filename="node${count}.shtml"
  echo "Redirect 301 /java/java_oo/${filename} http://www.devdaily.com/java/java_oo/"
  count=`expr $count + 1`
done

Shell script loop counter - discussion

As you can see from that shell script, I created a loop counter variable named "count", then create a while loop that terminates when the counter reaches a certain value, 200 in this example. I add one to the counter in the last line of the while loop, the one that looks like this:

count=`expr $count + 1`

Note that those are not single quotes in that statement, they are backticks, i.e., the character underneath the "~" character on your keyboard.

Shell script math/addition/counter example - summary

I hope this example shell script is helpful to you. I don't need to do something like this too often, maybe five or ten times a year, but I find that when I need a shell script to increment a counter, and count to a maximum value like this, it's nice to have an example shell script to copy and paste.