#!/bin/sh -u # $0 [pathname] # Word count non-comment lines, only in files that appear to be C++ programs. # Prompt for and read a pathname if not supplied on the command line. # -IAN! idallen@ncf.ca export PATH=/bin:/usr/bin umask 022 # Get the pathname from the command line or stdin. # case "$#" in 0) echo 1>&2 "Enter a file name:" read filename ;; 1) filename="$1" ;; *) echo 1>&2 "$0: Expecting one argument, found $# ($*)" exit 1 ;; esac # Check pathname for blanks or a non-C++ name. # case "$filename" in *" "*) echo 1>&2 "$0: '$filename' contains blanks" exit 1 ;; [a-z]*.cpp) # This case is a valid C++ pathname - do nothing. ;; *) echo 1>&2 "$0: '$filename' must start with a letter and end in .cpp" exit 1 ;; esac # Validate that the pathname is an existing file and is readable. # if [ ! -f "$filename" ]; then echo 1>&2 "$0: '$filename' is not an existing file" exit 1 fi if [ ! -r "$filename" ]; then echo 1>&2 "$0: '$filename' is not a readable file" exit 1 fi # Make sure the file starts with a correct #include line. # Bonus: Don't display any superfluous output on the screen. # line=$(head -1 "$filename") case "$line" in '#include ') # This case is a valid C++ #include line - do nothing. ;; *) echo 1>&2 "$0: '$filename' does not start with iostream.h" echo 1>&2 " Found: $line" exit 1 ;; esac # Make sure the file contains the string "main" somewhere. # Bonus: Don't display the superfluous grep output on the screen. # if ! grep main "$filename" >/dev/null ; then echo 1>&2 "$0: '$filename': Cannot find 'main'" exit 1 fi # Count the words in lines that do not contain comments. # Exit the script (bad status) if the counting fails. # count=$(grep -v // "$filename" | wc -w) || exit $? echo "File '$filename' contains $count non-comment words." # script exits with status of last command