Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: how to pass array items as options?

Tags:

bash

curl

I'm trying to generate headers for curl based on an array:

HEADERS=( "content-type: text/plain" "Authorization:  password" )

When I specify each one manually, it works:

curl --header  "${HEADERS[0]}"  --header  "${HEADERS[1]}" http://httpbin.org/headers

but when I try to generate automatically, curl complains:

curl `for H in "${HEADERS[@]}";do echo --header $H ;done` http://httpbin.org/headers
curl: (6) Could not resolve host: text
curl: (6) Could not resolve host: password
...

I've tried various quote escapes and evals with no luck. Can you suggest a way to make it work?

like image 976
AXE Labs Avatar asked Jun 25 '26 16:06

AXE Labs


1 Answers

A simple and concise solution, without loops:

HEADERS=( "content-type: text/plain" "Authorization:  password" )
curl "${HEADERS[@]/#/-H}" http://httpbin.org/headers

The substitution expression is performed independently on each array element, with the result being inserted as one word per array element (the same as "${HEADERS[@]}"). The # in the pattern means "only replace at the beginning. Writing the command-line option using -H instead of --header makes it much easier to add the option name to each string, since curl accepts -Hoption_value, whereas the normal command line syntax --header=option_value syntax is not accepted by curl. (Thanks to @wfr for pointing out that curl won't accept --header=....)

like image 106
rici Avatar answered Jun 27 '26 08:06

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!