This question already has an answer here:
I am attempting to do a curl command that uses a predefined variable as a header.
header='-H "Content-Type: application/json" -H "userGUID: 7feb6e62-35da-4def-88e9-376e788ffd97" -H "Content-Length: 51"'
And this is essentially the curl command
curl $header -w "http code: %{http_code}\\n" -X POST -d $BODY $URL
Which then returns the error message
rl: (6) Could not resolve host: application
curl: (6) Could not resolve host: 7feb6e62-35da-4def-88e9-376e788ffd97"
curl: (6) Could not resolve host: 51"
This works as expected
curl -H "Content-Type: application/json" -H "userGUID: 7feb6e62-35da-4def-88e9-376e788ffd97" -H "Content-Length: 51" -w "http code: %{http_code}\\n" -X POST -d $BODY $URL
The reason I'm trying to pass the header as a variable is because I'm writing a script that loops through and array, but currently this does not work with headers for some reason. There is no issue passing arguments for body.
Be aware that variable expansion in bash can catch people off guard easily.
A pretty good rule of thumb is to put double quotes around any variable you want to expand like
curl "$header" -w "http code: %{http_code}\\n" -X POST -d "$BODY" "$URL"
.Bash always expands
$SOMETHING
variables if they appear on their own, or if they appear in double quotes. (Not if they appear in single quotes).When expanded with double quotes they are treated as a single "token" by the shell, no matter what.
When expanded without double quotes they will be parsed as if you had typed their contents instead of the variable. So - if that variable had spaces, that may mean the shell will treat those as separators between arguments.