#!/bin/sh -u # $0 pathname # Tells whether a pathname is a file or directory. # Lists the contents of a directory; line counts a file. # # The syntax line, above, shows that this script expects one argument # and that argument is suposed to be a pathname (not a number or a userid). # The two lines that follow it give a quick synopsis of what the script does. # # 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 October 2001 # The PATH is necessary to make sure that the shell that executes # this script can find all the commands used in the script. # The umask sets the permissions on any files created. # This is a standard Unix path. It should work anywhere in the world, # for standard Unix commands. It does not include any X windows directories. # The umask here is appropriate for general-purpose scripts. It is not a # secure umask (077) that might be used for sensitive processing. # export PATH=/bin:/usr/bin umask 022 # Make sure we have exactly one argument to this script. # Issue an error message explaining what was expected and showing the # actual number of args found, followed by the text of those args. # Error messages always go on standard error, never standard output. # if [ "$#" -ne 1 ]; then echo 1>&2 "$0: Expecting exactly one argument; found $# ($*)" exit 1 fi # Test to see if the pathname is a directory. # List the contents and then exit, if it is. # Check the error code on the ls command. # if [ -d "$1" ]; then echo "'$1' is a directory; here is the content:" ls "$1" || exit $? exit 0 fi # Test to see if the pathname is a file. # Get a line count of lines and then exit, if it is. # Check the error code on the wc command. # By redirecting input from wc instead of using a command-line argument, # wc does not produce a file name in its output. That looks better. # if [ -f "$1" ]; then echo "'$1' is a file; here is a count of the lines:" lines=$(wc -l <"$1") || exit $? echo "It contains $lines lines" exit 0 fi # The command line argument is not a file or directory - print an error # message. Exit with some non-zero return status. (3 is arbitrary.) # Error messages always go on standard error, never standard output. # echo 1>&2 "$0: '$1' is not an existing file or directory" exit 3 # exit with some non-zero return status to indicate failure