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.

1

Open a blank plain text document in any text editor.

2

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

3

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

4

Type the following lines:

count=0

num=0<

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

5

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

6

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."

7

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.

8

Save the file as "count.sh."

9

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

10

Type the command "./count.sh" 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.