将命令行参数传递给另一个脚本

Pass commandline args into another script

我有几个相互调用的脚本。但是当我通过

来自 buid 的代码段-运行-node.sh

OPTIND=1 # Reset getopts in case it was changed in a previous run
while getopts "hn:c:f:s:" opt; do
    case "$opt" in
        h)
            usage
            exit 1
            ;;
        n)
            container_name=$OPTARG
            ;;
        c)
            test_command=$OPTARG
            ;;
        s)
            src=$OPTARG
            ;;
        *)
            usage
            exit 1
            ;;
    esac
done

$DIR/build-and-run.sh -n $container_name -c $test_command -s $src -f $DIR/../dockerfiles/dockerfile_node

来自构建的片段-run.sh

OPTIND=1 # Reset getopts in case it was changed in a previous run
while getopts "hn:c:f:s:" opt; do
    case "$opt" in
        h)
            usage
            exit 1
            ;;
        n)
            container_name=$OPTARG
            ;;
        c)
            test_command=$OPTARG
            ;;
        f)
            dockerfile=$OPTARG
            ;;
        s)
            src=$OPTARG
            ;;
        *)
            usage
            exit 1
            ;;
    esac
done

我这样称呼它

build-and-run-node.sh -n test-page-helper -s ./ -c 'scripts/npm-publish.sh -r test/test-helpers.git -b patch'

的意图是 npm-publish.sh 应该 运行 带有 -r 和 -b 参数。但是,当我 运行 脚本时,我得到

build-and-run.sh: illegal option -- r

这显然意味着它是 build-and-运行 命令正在使用 -r。我该如何避免这种情况?

在 buid-and-运行-node.sh 中,您需要在 $test_command 周围加上双引号,否则该变量将被拆分为白色 space 并且似乎包含buid-and-run.sh 的参数。像这样:

$DIR/build-and-run.sh -n $container_name -c "$test_command" -s $src -f $DIR/../dockerfiles/dockerfile_node

更多信息

正如下面的评论正确指出的那样,在 Bash 中引用 所有 变量是一种很好的做法,除非您知道要关闭它们(例如,启用shell 通配)。至少在变量名是较大单词的一部分的情况下,使用花括号来描述变量名也很有帮助。这是为了防止后面的字符被视为变量名 的一部分。因此,更好的命令调用可能如下所示:

"${DIR}/build-and-run.sh" -n "$container_name" -c "$test_command" -s "$src" -f "${DIR}/../dockerfiles/dockerfile_node"