#!/bin/sh -u # # $0 [filename] # # A script that chooses cases based on the number of characters # in the file that is the optional command line argument. # If no file name is given, we prompt for one. # # WARNING: Many of the comments in this file are "Instructor-Type" # comments and are *not* appropriate for real scripts. Do not put # "Instructor-Type" comments into the scripts that you submit for marking. # I put them in my example files because I am teaching you how to # write scripts; do not submit my teaching comments back to me again. # Read the week7.txt notes for more details on good comment style. # # -IAN! idallen@ncf.ca June 2001 # All scripts must start with lines similar to these two: # export PATH=/bin:/usr/bin umask 022 # The first thing all programs must do is validate their arguments. # # We do different things depending on the number of arguments given. # 0 args -> prompt for a file name. # 1 arg -> use the given file name. # >1 arg -> error. # The tr removes the newline normally added by "echo". # Prompts must always appear on stderr, not on stdout. # We output the "extra" arguments in case of error, so that the # user knows what s/he typed by mistake. # case "$#" in 0) echo "Enter a file name: " | tr -d '\n' 1>&2 read filename ;; 1) filename="$1" ;; *) echo 1>&2 "$0: Expecting 0 or 1 file name; found $# ($*)" exit 1 ;; esac # Real-world scripts probably would not do this echo: # echo "Processing file '$filename'." # Continue to validate the input. Validating input can take # up most of a script! # if [ ! -f "$filename" ]; then echo 1>&2 "$0: Argument '$filename' is not an existing file." exit 1 fi if [ ! -r "$filename" ]; then echo 1>&2 "$0: File '$filename' is not readable." exit 1 fi # The tr deletes the blanks around the number output by wc. # Redirecting input to wc avoids wc outputting the file name # (because there is no file name - wc is counting stdin). # The DEBUG line lets us know that the wc line worked; # remove it (comment it out) when the script is working. # nchars=$(wc -c <"$filename" | tr -d ' ') || exit $? echo "DEBUG The file contains $nchars characters." # Choose cases based on number of chars counted in the file. # Remember! First match wins - only one of these cases will execute. # case "$nchars" in 0) echo "The file is empty." ;; [0-9]) echo "The file contains 1-9 characters." ;; [0-9][0-9]) echo "The file contains 10-99 characters." ;; [0-9][0-9][0-9] | [0-9][0-9][0-9][0-9]) echo "The file contains 100-9999 characters." ;; *) echo "The file contains $nchars and that means it is big!" ;; esac exit 0