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

JavaScript

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

JavaScript

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

JavaScript

prints

JavaScript

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

JavaScript

which prints again

JavaScript

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.

JavaScript

Note that this is exactly equivalent to your second option:

JavaScript

-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