Home > Enterprise >  how to quote/use variables in curl
how to quote/use variables in curl

Time:03-09

This works correctly

curl --header 'Accept: application/json' www.example.com

However, how to achieve this (I want header information in a variable):

h="--header 'Accept: application/json'"                                                                                    
curl $h www.example.com                                                                                                         
curl: option --header 'Accept: application/json': is unknown
curl: try 'curl --help' or 'curl --manual' for more information

CodePudding user response:

In zsh, unquoted parameter expansions do not undergo word-splitting by default.

h="--header 'Accept: application/json'"
curl $h www.example.com  # equiv to curl "--header 'Accept: application/json'"

You could enable word-splitting, but then the single quotes remain part of the header.

curl ${(z)h} www.example.com  # equiv. to curl "--header" "'Accept: application/json'" www.example.com

What you want is an array, where the single quotes only serve to escape the space.

The solution is to use an array.

h=(--header 'Accept: application/json')
curl $h www.example.com  # equiv. to curl "--header" "Accept: application/json" www.example.com

The array parameter expands to a sequence of separate words, one per element.

  • Related