How to set variable in the curl command in bash?
To access variables, you have to put a dollar sign in front of the name: $name
However, variables do not get expanded inside strings enclosed in 'single quotes'. You should have them wrapped inside "double quotes" though, to prevent word splitting of the expanded value, if it might contain spaces.
So there are basically two ways, we either put the whole argument in double quotes to make the variable expandable, but then we have to escape the double quote characters inside, so that they end up in the actual parameter (command line shortened):
curl -d "{\"query\":\"$name\", \"turnOff\":true}" ...
Alternatively, we can concatenate string literals enclosed in different quote types by writing them immediately next to each other:
curl -d '{"query":"'"$name"'", \"turnOff\":true}' ...
Since the value for curls -d
parameter is within single quotes means that there will be no parameter expansion, just adding the variable would not work. You can get around this by ending the string literal, adding the variable and then starting the string literal again:
curl -d '{"query":"'"$name"'", "turnOff":true}' -H "Content-Type: application/json" -X POST http://localhost:8080/explorer
The extra double quotes around the variable are used to prevent unwanted shell parameter expansion.
@ByteCommander's answer is good, assuming you know that the value of name
is a properly escaped JSON string literal. If you can't (or don't want to) make that assumption, use a tool like jq
to generate the JSON for you.
curl -d "$(jq -n --arg n "$name" '{query: $n, turnOff: true}')" \
-H "Content-Type: application/json" -X POST http://localhost:8080/explorer