How to Increment a Counter in a Unix Shell Script

by Kristen Waters

Shell scripts are small programs written for a Unix shell or command line interpreter. One of the most commonly used Unix shell is the Bash shell -- it is installed on most Unix and Linux operating systems. You can use shell scripts to manipulate files, print files or execute programs. To increment a counter in a shell script, create a loop that adds one each time the condition of the loop is met.


Open a blank plain text document in any text editor.


Type "#!/bin/bash" -- without the quotations -- to start the shell script. This script uses the bash shell scripting language.


Type "names=( steve james sam jeff)" -- again, without the quotations -- to create an array of names.


Type the following lines:



This creates two variables set to zero. The "count" variable is used for the count; the "num" variable references each element in the array.


Type "len=${#names[@]}" -- without the quotations -- to create a variable that contains the number of elements in the array.


Type "while [ $count -lt $len ]" -- without the quotes -- to start the "while" loop that loops through the elements of the array. The "-lt" part of the statement stands for "less than."


Type the following lines:

count=expr $count + 1

echo "Name $count is ${names[$num]}"

num=expr $num + 1

This increments the "count" and "num" variables, and prints each element of the array.


Save the file as ""


Type "chmod +x" at a command prompt to make the script executable.


Type the command "./" to execute the script.

About the Author

Kristen Waters has been writing for the computer industry since 2004. She has written training materials for both large and small computer companies as well as how-to and informative articles for many online publications. She holds Bachelor of Science degrees from both York College of Pennsylvania and the University of Maryland.