使用空格动态构建命令行参数和值

时间:2016-03-15 21:01:13

标签: bash command-line-arguments

我有以下两个脚本:

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

我想了解$2 child.sh"thisthis is a value with spaces而非COMPOSITE_ARGS的原因。我想要实现的是通过多个脚本通过参数传递带空格的值,我没有得到正确的引用。

  1. 删除$COMPOSITE_ARGS引用的转义对我没有意义,因为这会产生分割。

  2. -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 合并为一个参数。

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

    Some()

1 个答案:

答案 0 :(得分:0)

你需要使用数组,否则你会发现每个参数都会在空格上分开:

$ 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]}"