Bourne/bash shell script for loop syntax

Home -> Programming -> Shell script -> Bourne shells

77066 views

From the computer of: Rex (39 recipes)
Created: Oct 29, 2003     Updated: Aug 30, 2004


1 comments:
View all comments

Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL

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

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.




1 Recipe comments: View comments

Bourne/bash shell script for loop syntax by Anonymous



Related recipes:

  Bourne/bash shell script: while loop syntax
  Bourne/bash shell scripts: case statement
  Bourne/bash shell script functions
  bash shell script iterate through array values
  Determine if a file is writable by a Bourne script user
  Bourne/bash shell scripts: if statement syntax
  Determine if file exists in a Bourne/bash shell script
  bash shell script accessing array variables
  Determine if a file is readable by current Bourne shell script user
  Hide password entry in Bourne/bash shell script

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.