Skip to content
Advertisement

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

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.)

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement