通过 Bash 中的串联将扩展变量作为另一个命令的参数

Expanded variable as argument of another command via concatenation in Bash

假设我想通过 $() 调用一些命令 some-command,参数存储在另一个变量 argument 中,后者包含 space.

  1. 根据我目前的理解,result="$(some-command $argument)"(例如扩展)导致传递两个参数这一事实是符合预期的。

  2. 问题部分:为什么result="$(some-command "$argument")"(例如连接)导致通过one[=的预期结果50=] 单个参数?

更多详情:

./some-command:

#!/usr/bin/env bash
echo "Arg 1: "
echo "Arg 2: "

./test-script:

#!/usr/bin/env bash

export PATH="`pwd -P`:$PATH"

argument="one two"

echo "Calling with expansion"
res="$(some-command $argument)"
echo $res

echo "Calling with concatenation"
res="$(some-command "$argument")"
echo $res

调用 test-script 会导致以下输出:

Calling with expansion
Arg 1: one Arg 2: two
Calling with concatenation
Arg 1: one two Arg 2:

我似乎不明白什么时候展开/评估 smth 以及如何将展开的变量分组为传递给脚本的参数。

谢谢!

P.S。额外的好奇心是 result="$(some-command \"$argument\")" 根本不起作用的原因。

这就是 bash 中引用和扩展的工作方式。事实上,= 后面的双引号是不需要的,因为没有进行分词,所以

result=$(some-command "$argument")

应该以同样的方式工作。

没有“串联”。 Bash 将 $() 中的字符串视为命令,并在 运行 之前对其运行所有扩展。

那么,some-command "$argument" 会发生什么?首先,参数扩展将 $argument 扩展为包含空格的字符串。当发生分词时,它会注意到该字符串用双引号引起来,因此它会将其保留为单个字符串。