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 5

Use printf to format and who to find the users. With option -q two lines will be displayed by who, the first contains the users, the second the number of them. Use head to select the first line of the output of who -q, then a for loop to print out each of them in turn. A count must also be made so as to know when to finish a line of output.

COUNT=""                       # Use to count to 4
ALLUSERS=$(who -q | head -1)   # Get the list of users
for i in $ALLUSERS             # Loop through in turn
do
    printf "%10s" $i           # Print each in width 10
    COUNT=$COUNT"x"            # Add an "x" to COUNT
    if   [ "$COUNT" = "xxxx" ] # If 4 "x"s in COUNT
    then printf "\n"           #   terminate the line
         COUNT=""              #   and reset COUNT
    fi
done

# At the end, if the final line contains less than
# four columns, that line must be terminated
if   [ "$COUNT" != "" ]
then printf "\n"
fi

Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck