简体   繁体   English

回显一个引用的引用数组

[英]echo a quoted array as quoted

The following code 以下代码

myopts=( --url="http://www.lemonde.fr" --out="hello world" --out-format="png" )
echo "going to execute following command: cutycapt ${myopts[@]}"
# commented out because this way you do not have to have cutycapt to test
# cutycapt "${myopts[@]}"

outputs the following: 输出以下内容:

going to execute following command: cutycapt --url=http://www.lemonde.fr --out=hello world --out-format=png

but really what is executed is: 但实际上执行的是:

cutycapt --url="http://www.lemonde.fr" --out="hello world" --out-format="png"

Thus, that is what I would like to be output from the echo command. 因此,这就是我希望从echo命令输出的内容。

When you create your array, its elements are subject to quote removal. 创建数组时,其元素会被引用删除。 If you want to keep them, you have to add them quoted already: 如果要保留它们,则必须添加已引用的它们:

$ myopts=( '--url="http://www.lemonde.fr"' '--out="hello world"' '--out-format="png"' )
$ echo "going to execute following command: cutycapt ${myopts[@]}"
going to execute following command: cutycapt --url="http://www.lemonde.fr" --out="hello world" --out-format="png"

If you look at your array elements after creating myopts , you'll see that they're already missing the quotes: 如果在创建myopts之后查看数组元素,您会发现它们已经缺少引号了:

$ myopts=( --url="http://www.lemonde.fr" --out="hello world" --out-format="png" )
$ (IFS=$'\n'; echo "${myopts[*]}")
--url=http://www.lemonde.fr
--out=hello world
--out-format=png

So it's not the expansion that removes them – it happens when assigning. 因此,并不是删除它们的扩展—在分配时会发生。

You can use printf with the %q format string to print a quoted version of the arguments like 您可以将printf%q格式字符串一起使用,以打印引号的引号版本,例如

printf '%q ' cutycapt "${myopts[@]}"; printf '\n'

(we add our \\n to the end since printf doens't automatically add one) (我们将\\n添加到末尾,因为printf不会自动添加一个)

Example: 例:

$ myopts=( --url="http://www.lemonde.fr" --out="hello world" --out-format="png" )
$ printf 'going to execute following command: '; printf '%q ' cutycapt "${myopts[@]}"; printf '\n'
going to execute following command: cutycapt --url=http://www.lemonde.fr --out=hello\ world --out-format=png

with the escape of the space in hello world hello world中的太空逃脱

Depending on why you want this, have you considered just running with set -x enabled, so you see the expanded command line before it's executed anyway? 根据您希望这样做的原因,您是否考虑过仅在启用set -x运行,因此您在执行扩展命令行之前还是会看到它?

$ set -x
$ cutycapt "${myopts[@]}"
+ cutycapt --url=http://www.lemonde.fr '--out=hello world' --out-format=png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM