Main index

Introducing UNIX and Linux


More on shells

Overview
Simple arithmetic
      Arithmetic expansion
            Operators for arithmetic expansion
      The 'expr' command
Pattern matching
      Patterns
            Examples of patterns
      The case statement
Entering and leaving the shell
More about scripts with options
Symbolic links
Setting up terminals
Conventions used in UNIX file systems
Summary
Exercises

Answer to chapter 8 question 3

This exercise requires the use of the test command at the start to perform the checks on the filename given as argument to the script, followed by a miscellany of UNIX utilities.

# Check number of arguments
if     [ $# -ne 1 ]
then   echo "Requires one argument"
       exit 1
# If a single argument, check it's readable
elif [ ! -r $1 ]
then   echo "File is unreadable"
       exit 1
fi

LINES=0           # To count number of lines
COL=0             # To count number of characters
while read LINE   # read returns false at end of input
do
   # Characters on line (including Newline)
   COLONLINE=$( echo "$LINE" | wc -c )
   # Add to COL and subtract 1 for the Newline
   COL=$(( $COL + $COLONLINE - 1 )
   # Increment line count
   LINES=$(( $LINES + 1 )
done <$1          # Input from the file

# Since 2 decimal places needed, must use bc to
#   calculate the average, not arithmetic expansion
AVERAGE=$( echo "scale=2; $COL / $LINES" | bc )

# Finally, display the average
printf "Average is %s\n" $AVERAGE

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck