Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a bash variable to pass multiple headers to curl command [duplicate]

Tags:

bash

curl

I would like to make curl request with multiple headers.The solution would be to make this command :

curl -H "keyheader: value" -H "2ndkeyheader: 2ndvalue" ...

My goal is to use only one variable with all the headers like :

headers='-H "keyheader: value" -H "2ndkeyheader: 2ndvalue" '
curl $headers

to send

curl -H "keyheader: value" -H "2ndkeyheader: 2ndvalue"

Currently, the problem is : I can use ' or " to declare my string, but bash tries to run what's after "-H" as arguments and then answers :

command unknown

Would like to know what is going wrong here.

like image 809
Maskim Avatar asked Sep 27 '17 14:09

Maskim


1 Answers

You just need to use an array and not a variable to pass the quoted strings.

declare -a curlArgs=('-H' "keyheader: value" '-H' "2ndkeyheader: 2ndvalue")

and now pass this array fully that way, the array expansion(with double-quotes) takes care of the arguments within double-quotes to be not split while passing.

curl "${curlArgs[@]}"

For more insight into why putting the args in your variables fail, see BashFAQ/050 - I'm trying to put a command in a variable, but the complex cases always fail!

like image 63
Inian Avatar answered Oct 06 '22 03:10

Inian