Mic*_*ael 3 bash shell command-line-arguments
假设我有一个a.sh要使用选项调用的脚本
a.sh -a1 a1option -a2 a2option
假设我还有一个 script b.sh,它调用a.sh并使用自己的选项。所以用户执行脚本如下:
b.sh -b1 b1option -b2 b2option -a1 a1option -a2 a2option
现在我想知道如何解析b.sh.
我不需要解析整个命令行。我不想b.sh知道选项a1和a2. 我只想获得选项b1,b2并将其余部分传递给a.sh.
你会怎么做?
根据要求,此方法避免解析整个命令行。只--收集 到的参数b.sh。然后去除 b 的参数,只将剩余的参数传递给a.sh。
b.sh 被调用 b.sh -b b1option -B b2option -- -a1 a1option -a2 a2option。在这一行中,双破折号--表示 的选项结束b.sh。下面解析--for use by之前的选项b.sh,然后从 the 中删除 b 参数,$@以便您可以将其传递给,a.sh而不必担心a.sh可能会给您带来什么错误。
while getopts ":b:B:" opt; do
case $opt in
b) B1=${OPTARG}
;;
B) B2=${OPTARG}
;;
esac
done
## strips off the b options (which must be placed before the --)
shift $(({OPTIND}-1))
a.sh "$@"
Run Code Online (Sandbox Code Playgroud)
注意:此方法使用 bash 内置的 getopts。getopts(与 getopt 相对,没有 s)只接受单字符选项;因此,我使用了bandB而不是b1and b2。
我最喜欢的getopts参考。