Bourne/bash shell script for loop syntax

Contributor Icon Contributed by Rex  
Tag Icon Tagged: Bourne shell scripting  

A for loop allows a program to iterate over a set of values. For loops in a Bourne shell script (sh, ksh, bash, zsh, etc.) are a useful means of iterating through files or other lists. This recipe describes the for loop syntax and provides some examples.


The basic for loop syntax is:

for var in list
do
commands;
done

The list can be a specified set of values (1 2 3 4) or anything that will evaluate into a set of values (a wildcard expression will expand the matching filenames into a list). For example, ‘/usr/bin/[aeiou]*’ will expand to the set of files in /usr/bin starting with a vowel (this, of course, comes up all the time). The commands enclosed between do and done will be executed once for each item in the list. The current value from the set can be accessed with the variable $var.

To separate a log file into multiple files based on the month (assuming that the log format contains the three letter month abbreviation):

#!/bin/sh
logfile="/var/adm/messages"
for mon in Sun Mon Tue Wed Thu Fri Sat
do
grep $mon $logfile > $logfile.$mon
done

 

1 Comment -


  1. rob a said on March 26, 2009

    So many websites have this same example of code, couldn’t you come up with something original?

 

RSS feed for comments on this post. TrackBack URL

Leave a comment -