从包含双引号的数组扩展参数 [英] expand arguments from array containing double quotes

查看:139
本文介绍了从包含双引号的数组扩展参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用bash中的从数组构建的参数来调用程序。

I want to call a program with arguments built from an array in bash.

我希望bash调用:

echo -arg1=simple -arg2="some spaces"

from array =(echo -arg1 =简单的 -arg2 = \一些空格\)或类似的(我可以调整项目的创建方式。)

from array=(echo -arg1=simple "-arg2=\"some spaces\"") or similar (I can adjust the way the items are created).

使用 $ {array [@]} bash调用:

echo -arg1=simple '-arg2="some spaces"'

但是我不希望使用单引号。如何正确构建和扩展数组?

But I do not want the single quotes. How to build and expand the array correctly?

#!/bin/bash
set -x

array=()
array+=(echo)
array+=(-arg1=simple)
array+=("-arg2=\"some spaces\"")

"${array[@]}"
"${array[*]}"
${array[@]}
${array[*]}



结果电话



Resulting calls

echo -arg1=simple '-arg2="some spaces"'
'echo -arg1=simple -arg2="some spaces"'
echo -arg1=simple '-arg2="some' 'spaces"'
echo -arg1=simple '-arg2="some' 'spaces"'


推荐答案

您可以像这样简单地做,而无需保留 echo 在数组内:

You can simply do it like this, no need to keep echo inside the array:

#!/bin/bash -x

array=()
array+=(-arg1=simple)
array+=(-arg2="some spaces")

echo "${array[@]}"

此结果将调用 echo 接收两个单词作为参数, -arg1 = s -arg2 =一些空格 ,就像您写的一样:

This results with a call to echo which receives two words as arguments, -arg1=simple and -arg2="some spaces", as if you wrote:

echo -arg1=simple -arg2="some spaces"

或者,您可以用 declare 在一行中定义数组:

Alternatively, you can define your array in one line, with declare:

declare -a array=(-arg1=simple -arg2="some spaces")

要检查如何扩展它,您可以使用 printf (我们在这里使用 == 只是为了清楚地显示开始和结束每个参数):

To check how it will be expanded, you can use printf (we use == here just to clearly show the beginning and ending of each argument):

$ printf "==%s==\n" "${array[@]}"
==-arg1=simple==
==-arg2=some spaces==

请注意在 $ {array [@]} 周围引号的重要性。它们确保将数组中的每个元素仅扩展为一个单词(就像在扩展之前在shell中引用一样)。与以下内容进行比较:

Note the importance of quotes around ${array[@]}. They ensure that each element in the array is expanded into only one word (like if quoted in shell before expansion). Compare that with:

$ printf "==%s==\n" ${array[@]}
==-arg1=simple==
==-arg2=some==
==spaces==

更新。如果要将其扩展为精确的 -arg2 =一些空格 (虽然不确定为什么要使用它),只需将其包装在定义中的单引号内即可:

Update. If you want to expand it to exactly -arg2="some spaces" (not sure why you would want it, though), just wrap it inside a single quotes on definition:

$ declare -a array=(-arg1=simple '-arg2="some spaces"')
$ echo "${array[@]}"
-arg1=simple -arg2="some spaces"
$ printf "==%s==\n" "${array[@]}"
==-arg1=simple==
==-arg2="some spaces"==

这篇关于从包含双引号的数组扩展参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆