每次致电getopts
始终处理“下一个”选项(通过检查确定)$OPTIND
),所以你的while
-loop 必然会按照选项出现的顺序处理选项。
既然你想要-c
要被其他选项部分取代,即使它在命令行上出现在它们之后,您也可以采取一些方法。
一种是循环选项twice:
#!/bin/bash
# ...
optstring='c:l:o:b:dehruwx'
while getopts "$optstring" OPTION
do
case $OPTION in
c)
echo "load"
CONFIG_FILE=$OPTARG
# load_config is a function that sources the config file
load_config $CONFIG_FILE
esac
done
OPTIND=1
while getopts "$optstring" OPTION
do
case $OPTION in
l)
echo "set local"
LOCAL_WAR_FILE=$OPTARG
;;
# ...
esac
done
shift $(($OPTIND - 1))
另一种是将选项保存在变量中-c
won't覆盖,然后将它们复制过来:
#!/bin/bash
# ...
while getopts c:l:o:b:dehruwx OPTION
do
case $OPTION in
c)
echo "load"
CONFIG_FILE=$OPTARG
# load_config is a function that sources the config file
load_config $CONFIG_FILE
;;
l)
echo "set local"
LOCAL_WAR_FILE_OVERRIDE=$OPTARG
;;
# ...
esac
done
shift $(($OPTIND - 1))
LOCAL_WAR_FILE="${LOCAL_WAR_FILE_OVERRIDE-${LOCAL_WAR_FILE}}"
(或者,相反,配置文件可以设置诸如LOCAL_WAR_FILE_DEFAULT
,然后你会写LOCAL_WAR_FILE="${LOCAL_WAR_FILE-${LOCAL_WAR_FILE_DEFAULT}}"
.)
另一种选择是要求-c
,如果在场,请来first。您可以通过先自己处理来做到这一点:
if [[ "$1" = -c ]] ; then
echo "load"
CONFIG_FILE="$2"
# load_config is a function that sources the config file
load_config "$CONFIG_FILE"
shift 2
fi
然后在你的主要while
-循环,只需处理-c
通过打印错误消息。
另一种方法是简单地记录您现有的行为并将其称为“功能”。许多 Unix 实用程序都有较新的选项取代较早的选项,因此这种行为并不是真正的问题。