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

Answer to chapter 7 question 7

You need to keep a count of the number of the line, which can be incremented with the aid of bc. Use read to read in the standard input line-by-line, and printf to ensure that the format is the same as cat -n (i.e. six character columns for the line number, followed by two blank spaces, followed by the line).

LINENUMBER=1          # To store the line number
while read LINE       # 'read' returns false at end
do                    #          of input
   # Print the line number and the line
   printf "%6d  %s\n" $LINENUMBER $LINE
   # Add one to the line number
   LINENUMBER=$( echo "$LINENUMBER + 1" | bc )
done

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck