(很明显,这个问题主要涉及如何将信息应用于手动定义的数组getopts
以及如何将 ashift
应用于手动定义的数组。
我正在为一些 Bash 函数的启动编写一个过程,该过程以通常的getopts
方式解析函数的参数,同时也解析意外的参数(通过循环getopts
处理多次)。
在下面的代码中可以看到一个小函数process_arguments()
,它基本上包含getopts
处理和shift
作用于位置参数的结束操作。因为这个参数解析的整个过程是针对函数而不是脚本的,所以我想将函数中包含的处理移到脚本process_arguments
的主while
循环中。这涉及对函数中过程的输入和输出信息的修改。
处理的输入信息getopts
可以传递到getopts
数组中args
:
getopts optstring name [args]
但是,我不确定如何更改过程的输出。目前,它移动位置参数,然后打印位置参数(echo "${@}"
)。
那么,问题...
- 这种
getopts
args
方法是将信息传递给程序的正确方法吗? - 如何将 应用于
shift
传递给的参数,getopts
然后如何将这些移位的参数输出到脚本处理的其余部分?
谢谢你的帮助。我欢迎任何其他指导。总体目标是删除该函数process_arguments()
并将其功能合并到主“while”循环中。
#!/bin/bash
################################################################################
#
# This is a test of command line parameter parsing that is explicitly non-POSIX.
# This approach handles
# - options (for getopts)
# - arguments of options (for getopts)
# - positional arguments (for getopts) and
# - non-option arguments (command line parameters not expected by getopts).
# All non-option arguments are placed in the string non_option_parameters. The
# silent error reporting mode of getopts is required. Following command line
# parameter parsing, input information can be accepted based on internal
# priority assumptions.
#
# example usage:
# ./script.sh
# non-option parameters:
# ./script.sh -a Dirac
# -a triggered with parameter Dirac
# non-option parameters:
# ./script.sh -a Dirac -b
# -a triggered with parameter Dirac
# -b triggered
# non-option parameters:
# ./script.sh -a Dirac Feynman -b
# -a triggered with parameter Dirac
# -b triggered
# non-option parameters: Feynman
# ./script.sh -a Dirac Feynman Born -b
# -a triggered with parameter Dirac
# -b triggered
# non-option parameters: Feynman Born
# ./script.sh -a Dirac Feynman Born Born -b
# -a triggered with parameter Dirac
# -b triggered
# non-option parameters: Feynman Born
# ./script.sh -a Dirac Feynman Born Born -b
# -a triggered with parameter Dirac
# -b triggered
# non-option parameters: Feynman Born Born
#
################################################################################
process_arguments(){
OPTIND=1
while getopts "${option_string}" option; do
case ${option} in
a)
echo "-a triggered with parameter "${OPTARG}"" >&2 # output to STDERR
;;
b)
echo "-b triggered" >&2 # output to STDERR
;;
\?)
echo "invalid option: -"${OPTARG}"" >&2 # output to STDERR
;;
esac
done
shift $(expr ${OPTIND} - 1)
echo "${@}"
}
option_string=":a:b"
non_option_parameters=""
parameters="${@}"
while [ ! -z "${parameters}" ]; do
parameters="$(process_arguments ${parameters})"
non_option_parameters="${non_option_parameters} "$(awk -F '[ \t]*-' '{print $1}' <<< "${parameters}")
parameters=$(awk -F '[ \t]*-' 'NF > 1{print substr($0, index($0, "-"))}' <<< "${parameters}")
done
echo "non-option parameters:${non_option_parameters}"