Reputation: 46914
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.
Upvotes: 0
Views: 901
Reputation: 8174
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.
Upvotes: 2