我有以下两个脚本:
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
中"this
为this is a value with spaces
而非COMPOSITE_ARGS
的原因。我想要实现的是通过多个脚本通过参数传递带空格的值,我没有得到正确的引用。
删除$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
合并为一个参数。
有什么想法吗?我想要实现的是:
Some()
答案 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]}"