无论是外置的getopt命令,亦或是bash内置的getopts函数,都对bash脚本的传入参数做了一些规定,比如强制规定了短参数"-t 1",长参数“--test 1”。但是现实环境的脚本参数是杂乱无章的,不光是长短参数结合的, 还有类似这样的参数"-test 1", 注意了是长参数的基础上少一个减号“-”。如此混乱的传入参数,如何解析,是一个令人头大的难题。
针对不规范的参数"-test 1", 使用getopt命令的“-a”参数。
注释:“-a, --alternative Allow long options starting with single -”
wll@linux:~/wll/temp$ getopt -h
Usage:
getopt optstring parameters
getopt [options] [--] optstring parameters
getopt [options] -o|--options optstring [options] [--] parameters
Options:
-a, --alternative Allow long options starting with single -
-h, --help This small usage guide
-l, --longoptions <longopts> Long options to be recognized
-n, --name <progname> The name under which errors are reported
-o, --options <optstring> Short options to be recognized
-q, --quiet Disable error reporting by getopt(3)
-Q, --quiet-output No normal output
-s, --shell <shell> Set shell quoting conventions
-T, --test Test for getopt(1) version
-u, --unquoted Do not quote the output
-V, --version Output version information
以下以解析2个参数“-upgrade” 和“-upath”为例。
#!/bin/bash
upgrade_lable=0
update_path=/tmp/up_path
# parse cmd line args: -upgrade and -upath
ARGS=`getopt -a -q -o "" -l "upgrade:,upath:" -- $@`
if [ $? != 0 ]; then
echo "getopt parsed all input args, but failed to parsed a part of..."
fi
echo ARGS=[$ARGS]
# set formated args to ($1, $2, ...)
eval set -- "${ARGS}"
echo formatted parameters=[$@]
while true
do
case "$1" in
--upgrade)
echo "Option upgrade argument $2";
upgrade_lable=$2
shift 2
;;
--upath)
echo "Option upath argument $2";
update_path="$2"
shift 2
;;
--)
shift
break
;;
*)
echo "Internal error!, argument $1";
shift
;;
esac
done
echo "update_path=${update_path}"
echo "upgrade_lable=${upgrade_lable}"
希望对大家的脚本参数解析有所帮助。