Home‎ > ‎CIS 98‎ > ‎

Lab 10: Looping Constructs

The purpose of this lab is to use various forms of looping constructs to repeatedly execute blocks of code. 


Programs spend the overwhelming majority of compute time running loops. That's because loops are the place that most useful work gets done. In this lab you'll use loops to do various tasks in the shell. The programs in this lab use the find UNIX command. You should prepare by reading my brief tutorial on find: 


Looping constructs often require a counter to control how many times through the loop the execution should go. Use the ((...)) syntax to evaluate the following expressions, and assign the result into the variable, NUMBER:

7 + 5 - 2
3 - -2
7 + 3 * 8
(7 + 3)* 8
"$NUMBER" * 7
"$NUMBER" / 5
"$NUMBER" % 5
"$NUMBER" % 60
"$NUMBER" / "$DIV"
the length of "abcdefghij" (hint: remember the ${#} syntax)
the substring "cdefg" from the string: "abcdefghij" (hint: use the ${variable:start:length} syntax)

In the following code samples correct the syntax errors so that the code executes correctly.

Sample 1:
while true
    echo $COUNT
    COUNT=`expr COUNT + 1`

Sample 2:
until [ $# -gt 0 ]
    echo $1; shift

Sample 3:
for $USER in johnsdan whitelex trippedw bogaajef morgaarc
    write $USER << EOF
Don't forget the meeting starts in 5 minutes. See you there!

Sample 4:
for NAME in $* do
    echo the next name is $NAME

Test your corrected loops!

Programming Assignment

For this assignment, you will write two programs: the first, tally, takes a directory name on the command line and reports how many of the files within that directory are regular files, directories, symbolic links, or other.
  1. Give a usage message if a command line argument is not supplied or if the argument is not a valid directory.
  2. Extra credit: Allow multiple directories to be specified on the command line, and analyze each one separately.
Example execution:
$ tally /etc
    Regular files: 143
    Directory files: 114
    Symbolic links: 16
    Other types: 0

The second program will be named search, and will process command line arguments to find out what it is supposed to find.

If no command line arguments are given, your output should be:
    Searching for all files under the current working directory.
    [file list here]

Give the following usage message if a command line option (--help) is given:
    usage: search [-d directory] [-f filename] [-u user] [ -t type] [--help]

Example execution:
$ search -f myfile -d / -u matera

Hint: Look at how Frodo (/home/cis98/bin/frodo) parses his command line arguments starting near line 326.

Turn In

Create a lab 10 directory and place the two program files in it: 
  1. ~/lab10/tally
  2. ~/lab10/search


  1. 10 points for tally
  2. 10 points for search