expand arguments from array containing double quotes

柔情痞子 提交于 2020-01-05 02:31:32

问题


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

I want bash to call:

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

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

Problem

With "${array[@]}" bash calls:

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

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

Example code

#!/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"'

回答1:


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[@]}"

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"

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

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

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==

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==

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"==



回答2:


"${array[@]}" is correct. The -x option simply chooses a canonical way to display values that require quoting, and '-arg2="some spaces"' is equivalent to "-arg2=\"some spaces\"".



来源:https://stackoverflow.com/questions/45325659/expand-arguments-from-array-containing-double-quotes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!