Source code in KshOptionParsingSimple.sh

To see how this is used return to this tutorial index.

#!/bin/ksh -u
# How to process long options in the shell.
# This works with:
# * the Korn shell:
#	pdksh -- a clone of the Korn shell (ksh)
#	KSH-93 -- the KornShell by David Korn of AT&T Bell Laboratories.
# * bash, not sure which versions
# This is a simpler script that just recognised --help, which is often enough

# **** Shell Script Template ****

# SCCS: @(#)	1.4 10/20/21 23:19:25
# Author: Alain D D Williams, addw@phcomp.co.uk, 2009


PROGNAME=${0##*/}

Verbose=0

# Print the message to stderr and exit.
function Die {
	echo "$PROGNAME: $*" >&2
	exit 2
}

# Generate a note that will be seen by the user -- even if redirected
function Note {
	(( Verbose > 0 )) && echo "$PROGNAME: $*" >&2
}

# Print a usage message & exit the program.
# If an argument is given print that as an error and exit 1
function Usage {
	(( $# > 0 )) && echo "$PROGNAME: $*" >&2
	cat <<-!
		This program does X Y Z
		Usage: $PROGNAME [-opts] [files ...]
		-d		Something that takes an argument
		-v		Verbose (multiple use gives more verbosity)
		-x, --help	eXplain
		Version: 1.4 10/20/21
		!
	exit $#
}

# Parse options, recognise the --help option
while	(( $# >= OPTIND )) && eval A=\${$OPTIND} || A=
	if [[ $A == --help ]]
	then	(( OPTIND++ ))
		opt=help
	else	getopts :d:vx opt
	fi
do	case "$opt" in
	d)	echo "Dee arg=$OPTARG" ;;
	v)	(( Verbose++ )) ;;
	x|help)	Usage ;;
	:)	Usage "Missing argument to option '$OPTARG'" ;;
	\?)	Usage "Unknown option '$OPTARG'" ;;
	*)	Usage "Internal program error, unrecognised argument '$opt'" ;;
	esac
done
shift $(( OPTIND - 1 ))

echo "Verbose=$Verbose"
echo "End opts processing - OPTIND=$OPTIND, #args: $#"
(( $# >= 1 )) && echo "Args are: $@"

# Now process the arguments as files:
for file
do	Note "Processing $file"
	# Do something
	[[ -f $file ]] && ls -l $file || Die "Cannot see $file"
done

# end

Return to this tutorial index.