假设我有一个脚本 a.sh
可以通过选项调用
a.sh -a1 a1option -a2 a2option
假设我还有一个脚本 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
的选项结束。下面解析 --
之前的选项供 b.sh
使用,然后从 $@
中删除 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 "$@"
注意:此方法使用 bash 内置的 getopts。 Getopts(相对于 getopt,没有 s)只接受单字符选项;因此,我使用了 b
和 B
而不是 b1
和 b2
。
我的最爱getopts引用。
关于bash - 将命令行选项传递给 bash 中调用的脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18965305/