Consider this simple bash script : (I am writing myurl
as a placeholder for the correct URL; and myhost
as the placeholder for the correct hostname for privacy here.)
for a in `seq 400 450`; do
curl --request POST \
--url myurl \
--header 'Content-Type: application/json' \
--header 'Host: myhost' \
--data '{
"devID": "21010010",
"count": 0,
"fileEnd": 1,
"line": "",
"file": "$a"
}'
done
This is rejected as bad request. I want, the output of seq
, (e.g. the number 410) to be a quote delimated string. Notice the line "file": "$a"
. If I write "file": "410"
, this works perfectly, and also for any other file between 400 and 450 - as long as it is surrounded by ""
quotes.
Question :
I want, that in each iteration of the loop, the curl request should include the number coming from the seq
command surrounded by ""
. So the first call should be :
curl --request POST \
--url myurl \
--header 'Content-Type: application/json' \
--header 'Host: myhost' \
--data '{
"devID": "21010010",
"count": 0,
"fileEnd": 1,
"line": "",
"file": "400"
}'
The next one to be :
curl --request POST \
--url myurl \
--header 'Content-Type: application/json' \
--header 'Host: myhost' \
--data '{
"devID": "21010010",
"count": 0,
"fileEnd": 1,
"line": "",
"file": "401"
}'
and so on.
How can I do this? Thank you.
The --data
portion is wrapped in single quotes ...
'{"devID": ... "file": "$a"}'
... which disables the expansion of variable references inside said single quotes.
Consider:
$ a=410
$ echo '"devID": "21010010", "file": "${a}"'
"devID": "21010010", "file": "${a}" # ${a} not expanded
You could wrap the --data
section in double quotes, but then you need to also escape all of the nested double quotes.
Another idea is to break the --data
section into 2x sections wrapped in single quotes and place the ${a}
reference between the 2x sections, eg:
$ echo '"devID": "21010010", "file": "'${a}'"' # change "${a}" to "'${a}'"
"devID": "21010010", "file": "410" # ${a} successfully expanded
NOTE: There are several posts regarding the difference between single and double quotes, eg, this link