3

假设我有一个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知道选项a1a2. 我只想获得选项b1b2然后将其余的传递给a.sh.

你会怎么做?

4

3 回答 3

6

根据要求,此方法避免解析整个命令行。--只为 收集高达 的参数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 "$@"

注意:此方法使用 bash 内置 getopts。Getopts(相对于 getopt,没有 s)只接受单字符选项;因此,我使用bandB而不是b1and b2

我最喜欢的getopts参考。

于 2013-09-23T18:51:40.167 回答
3

你可以这样做:

#!/bin/bash

while [[ $# -gt 0 ]]; do
    case "$1" in
    -b1)
        B1=true
        B1OPT=$2
        shift
        ;;
    -b2)
        B2=true
        B2OPT=$2
        shift
        ;;
    --)
        shift
        break
        ;;
    *)
        echo "Invalid option: $1"
        exit 1  ## Could be optional.
        ;;
    esac
    shift
done

bash a2.sh "$@"

请注意,您应该将变量$@放在双引号内,以防止展开时分词。

于 2013-09-23T19:29:04.023 回答
2

如果 a.sh 可以忽略它不知道的选项,您可以使用 b.sh 被调用的所有选项来调用它:

a.sh "${@}"
于 2013-09-23T17:35:51.957 回答