0

I am writing a script which uses CURL.

There are some HTTP headers common to all requests.

curl -X GET "..." -H  'accept: */*' -H "api-key: $API_KEY"

So I would like to put those to a variable:

HEADERS="-H  'accept: */*' -H \"api-key: $API_KEY\""

curl -X GET "..." $HEADERS      ### <-- This is what I want to achieve.

As you can see, it needs a mix of

  • 's because it contains *, which could expand,
  • "s because there is a variable.

I have tried quite a few combinations of escaping, mixing ' and ", building the string gradually, but always I end up with Bash adding unwanted escapes or leaving those which I need.

How can I achieve to have both -H params (i.e. all 4 arguments) in a variable which I can then use in a command?

There are a few similar questions but they are specific for other cases.

Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
  • What you tried seem to work for me on MacOS with bash 3.2.57. Perhaps you are using an older/bogus version ? ``` $ export API=123; HEADERS="-H 'accept: */*' -H \"api-key: $API\""; echo $HEADERS -H 'accept: */*' -H "api-key: 123" ``` – Francozen Mar 25 '20 at 12:40
  • Possible duplicate of [Why does shell ignore quotes in arguments passed to it through variables?](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quotes-in-arguments-passed-to-it-through-variables) – oguz ismail Mar 25 '20 at 12:54
  • You should use an array instead of a string. – Benjamin W. Mar 25 '20 at 13:26

1 Answers1

1

What you want to do is to store a list of words (like, -H or accept: */*) where each word may contain whitespace characters. As bash delimits words in a string by whitespace (by default), it's difficult to use a string variable for a list of words that possibly contain whitespace characters.

A simple solution is to use a list variable. Each list member is a word (and it can thus contain whitepace as needed). When expanding that list, ensure proper quoting. In your case:

declare -a HEADERS
HEADERS=(
  '-H' 'accept: */*'
  '-H' 'api-key: $API_KEY'
)
curl -X GET "..." "${HEADERS[@]}"

Mind the "..." characters when expanding the array. They will ensure that each list item is expanded as a single, dedicated word.

Alex O
  • 7,746
  • 2
  • 25
  • 38