back toc next

Handling Command Line Options

Solution 2 -- using getopts

#!/bin/sh

verbose=off
filename=

while getopts vf: opt; do
    case "$opt" in
	v)  verbose=on;
	    ;;
	f)  if [ -f "$OPTARG" ]; then
		filename=$OPTARG
	    else
		echo >&2 no such file \"$OPTARG\".
		exit 1
	    fi
	    ;;
	*)  echo >&2 $0: no such option "$opt"
            echo >&2 "usage: $0 [-v] [-f file] [file ...]"
	    exit 1
	    ;;
    esac
done

#the trailing arguments are now in $1, $2, $3,...