【问题标题】:Pass commandline args into another script将命令行参数传递给另一个脚本
【发布时间】:2016-10-14 16:28:43
【问题描述】:

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

来自 buid-and-run-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

来自 build-and-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

这显然意味着使用 -r 的是 build-and-run 命令。我该如何避免这种情况?

【问题讨论】:

  • shellcheck.net 会自动为您捕捉到这一点,无需人工审核。

标签: bash shell getopts


【解决方案1】:

您需要在 buid-and-run-node.sh 中将 $test_command 用双引号括起来,否则该变量将在空白处拆分,并且似乎包含 buid-and-run.sh 的参数。像这样:

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

更多信息

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

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

【讨论】:

  • 还不如在其他地方添加引号,而您在使用它时会丢失它们,不是吗?最好鼓励人们仅在他们明确想要这些行为的扩展中启用字符串拆分和通配符(通过省略引号),而不是让它们默认开启然后根据需要关闭;在后一种情况下,脚本的正确性与在确定存在必要性时所执行的测试用例的广度密切相关。
猜你喜欢
  • 2022-12-08
  • 2014-03-08
  • 2013-10-22
  • 2016-12-19
  • 1970-01-01
  • 2013-10-11
  • 1970-01-01
  • 2018-10-16
  • 1970-01-01
相关资源
最近更新 更多