【问题标题】:Dynamically building command line arguments and values with spaces使用空格动态构建命令行参数和值
【发布时间】:2016-03-16 05:05:47
【问题描述】:

我有以下 2 个脚本:

main.sh:

#!/bin/bash

ARG_WITH_SPACES="this is a value with spaces"
COMPOSITE_ARGS="-p $ARG_WITH_SPACES"

echo "main.sh will run:"
echo "  ./child.sh $COMPOSITE_ARGS"
./child.sh $COMPOSITE_ARGS

child.sh:

#!/bin/bash

echo "child.sh received:"
echo "  1: $1"
echo "  2: $2"

如果我运行main.js,我会得到:

main.sh will run:
  ./child.sh -p "this is a value with spaces"
child.sh received:
  1: -p
  2: "this

我试图理解为什么child.sh 中的$2"this 而不是this is a value with spaces。我想要实现的是通过参数通过多个脚本传递带有空格的值,而我没有得到正确的引用。

  1. 删除来自COMPOSITE_ARGS 的转义引用对我来说毫无意义,因为这会产生拆分。

  2. $COMPOSITE_ARGS 周围加上引号是没有意义的,因为这会将-p"this is a value with spaces" 合并为一个参数。

有什么想法吗?我想要实现的是:

main.sh will run:
  ./child.sh -p "this is a value with spaces"
child.sh received:
  1: -p
  2: this is a value with spaces

【问题讨论】:

    标签: bash command-line-arguments


    【解决方案1】:

    您需要使用一个数组,否则正如您所观察到的那样,每个参数将被分割为空格:

    $ arg="hello world"
    $ arg2="john doe"
    $ comp_args=("-l" "$arg" "$arg2");
    $ ls "${comp_args[@]}"
    ls: cannot access hello world: No such file or directory
    ls: cannot access john doe: No such file or directory
    

    希望你明白这一点。

    在你的例子中:

    ARG_WITH_SPACES="this is a value with spaces"
    COMPOSITE_ARGS=("-p" "$ARG_WITH_SPACES")
    
    bash child.sh "${COMPOSITE_ARGS[0]}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-24
      • 2018-11-10
      • 2014-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      相关资源
      最近更新 更多