如何在数组中存储包含双引号的命令参数

如何在数组中存储包含双引号的命令参数

本文介绍了如何在数组中存储包含双引号的命令参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Bash脚本,它可以生成,存储和修改数组中的值.这些值以后将用作命令的参数.

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

对于MCVE,我想到了一个任意命令 bash -c'echo 0 ="$ 0";echo 1 ="$ 1"'解释了我的问题.我将使用两个参数 -option1 = withoutspace -option2 ="with space" 调用命令.所以看起来像这样

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"

如果对命令的调用将直接输入到shell中.它打印

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

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

在我的Bash脚本中,参数是数组的一部分.但是

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

打印

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

再次打印

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

要使 ARGUMENTS + =('-option2 ="with space"')以及 ARGUMENTS + =('-option2 = with space'] ?

(也许将命令的参数存储在数组中甚至是完全错误的?我愿意提出建议.)

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

推荐答案

删除单引号.完全按照在命令行中的方式编写选项.

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 =带空格" '-option2 =带空格'都计算为同一字符串.它们是写同一件事的两种方式.

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

这是完全正确的事情.数组对此是完美的.使用扁平字符串将是一个错误.

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

这篇关于如何在数组中存储包含双引号的命令参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 16:13