内置的getopts可以在函数内部使用,以编写容纳标志和可选参数的函数。这没有什么特别的困难,但是必须适当处理getopts涉及的值。例如,我们定义了一个failwith函数,该函数在stderr上写一条消息,并以代码1或作为-x选项参数提供的任意代码退出:
# failwith [-x STATUS] PRINTF-LIKE-ARGV
# Fail with the given diagnostic message
#
# The -x flag can be used to convey a custom exit status, instead of
# the value 1. A newline is automatically added to the output.
failwith()
{
local OPTIND OPTION OPTARG status
status=1
OPTIND=1
while getopts 'x:' OPTION; do
case ${OPTION} in
x) status="${OPTARG}";;
*) 1>&2 printf 'failwith: %s: Unsupported option.\n' "${OPTION}";;
esac
done
shift $(( OPTIND - 1 ))
{
printf 'Failure: '
printf "$@"
printf '\n'
} 1>&2
exit "${status}"
}该功能可以如下使用:
failwith '%s: File not found.' "${filename}"
failwith -x 70 'General internal error.'等等。
请注意,对于printf,变量不应用作第一个参数。如果要打印的消息包含变量的内容,则应使用说明%s符来打印它,例如
failwith '%s' "${message}"