How to store command arguments which contain double quotes in an array?

不羁岁月 提交于 2021-02-10 06:45:50

问题


I have a Bash script which generates, stores and modifies values in an array. These values are later used as arguments for a command.

For a MCVE I thought of an arbitrary command bash -c 'echo 0="$0" ; echo 1="$1"' which explains my problem. I will call my command with two arguments -option1=withoutspace and -option2="with space". So it would look like this

> bash -c 'echo 0="$0" ; echo 1="$1"' -option1=withoutspace -option2="with space"

if the call to the command would be typed directly into the shell. It prints

0=-option1=withoutspace
1=-option2=with space

In my Bash script, the arguments are part of an array. However

#!/bin/bash
ARGUMENTS=()
ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2="with space"')
bash -c 'echo 0="$0" ; echo 1="$1"' "${ARGUMENTS[@]}"

prints

0=-option1=withoutspace
1=-option2="with space"

which still shows the double quotes (because they are interpreted literally?). What works is

#!/bin/bash
ARGUMENTS=()
ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2=with space')
bash -c 'echo 0="$0" ; echo 1="$1"' "${ARGUMENTS[@]}"

which prints again

0=-option1=withoutspace
1=-option2=with space

What do I have to change to make ARGUMENTS+=('-option2="with space"') work as well as ARGUMENTS+=('-option2=with space')?

(Maybe it's even entirely wrong to store arguments for a command in an array? I'm open for suggestions.)


回答1:


Get rid of the single quotes. Write the options exactly as you would on the command line.

ARGUMENTS+=(-option1=withoutspace)
ARGUMENTS+=(-option2="with space")

Note that this is exactly equivalent to your second option:

ARGUMENTS+=('-option1=withoutspace')
ARGUMENTS+=('-option2=with space')

-option2="with space" and '-option2=with space' both evaluate to the same string. They're two ways of writing the same thing.

(Maybe it's even entirely wrong to store arguments for a command in an array? I'm open for suggestions.)

It's the exact right thing to do. Arrays are perfect for this. Using a flat string would be a mistake.



来源:https://stackoverflow.com/questions/47665076/how-to-store-command-arguments-which-contain-double-quotes-in-an-array

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