Main index

Introducing UNIX and Linux


Introduction to shells

Overview
Why do we need a shell?
Shell syntax
      Types of shell command
      Simple commands
      Pipelines
      Grouping commands
      Exit status
      List commands
Arithmetic
      Operators and functions
Making decisions
      The 'test' statement
            Operators used by 'test'
      The 'if' statement
Loops
      'For' loops
      'While' and 'until' loops
Searching for files
      Arguments to 'find'
Formatted output
      Arguments to 'printf'
Passing information to scripts
      Scripts with arguments
      Parameter expansion
Summary
Exercises

'For' loops

The for loop is a method of executing a section of a script for a specified (and fixed) number of times. For instance, to page, in sequence, each readable file in the current directory:

for i in $( ls )
do
>   [ -r $i ] && more $i
done

The syntax for the for loop is

for name in values
do
  commands
done

and this causes the variable name to be set in turn to each word in values, and commands executed with name set to that value. So, in the above example, $( ls ) becomes a list of the files in the current directory, and variable i is set to each one in turn. The filename, which is the value of i, is tested to see if it is readable, and if so it is paged using more.

Worked example

Send a personalised greeting (such as Hello jo) to each of the users jo, sam and george:
Solution: You cannot simply use mailx jo sam george, as they would then each receive the same (unpersonalised) message. So you should instead use a for loop to create each message in turn and then mail it to the appropriate user.

for user in jo sam george
do
echo "Hello $user" | mailx $user
done


Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck