Bash 处理标志和可选参数
示例
内置的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}"
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿