0

Here is the curl which works perfectly fine

curl --user "A:B"  --digest --header "Accept: application/json" --header "Content-Type: application/json" --request POST "http://localhost:8080/api/private/foo/bar" --data '["123456"]'

I wanted to run this in a for loop so I wrote this code

Orgs=(
    "123456"
    "333444"
)

for i in ${Orgs[@]} 
do
 curl --user "A:B"  --digest --header "Accept: application/json" --header "Content-Type: application/json" --request POST "http://localhost:8080/api/private/foo/bar" --data '"["\"${i}\""]"'
done 

However this does not work since --data is not well formatted. The single quotes are needed in curl to send data --data '["123456"]' but single quotes, are not working as expected in shell script.

How can I fix my curl in shell script to work out ?

JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
  • `--data "[\"$i\"]"` is your easiest bet. – Charles Duffy Aug 25 '20 at 18:56
  • For _complex_ data your best bet is to use `jq` to insert it into a JSON document, and we have Q&A entries in the knowledgebase describing how to do that and feed the output to curl. As long as your values are just simple numbers, though, that's overkill. – Charles Duffy Aug 25 '20 at 18:57
  • 1
    BTW, `--data '["'"$i"'"]'` would work too, but again, harder to read than just using a single double-quoted context. The important thing to realize is that you can change quoting contexts inside a single string. In that context, you have `'["'` as a single-quoted string containing `["`, then `"$i"` as a double-quoted string expanding to the contents of your variable `i`, and then `'"]'` as a second single-quoted string, this time with the data `"]`. Combine them all together, and you get something like `["123456"]`. – Charles Duffy Aug 25 '20 at 18:59
  • @CharlesDuffy works like a charm – JavaDeveloper Aug 25 '20 at 19:18
  • 1
    BTW, consider making it `for i in "${Orgs[@]}"`, with the quotes. Doesn't matter with the data you have right now, but as soon as your array contains values with spaces, values that can be interpreted as wildcards, &c., it'll be pertinent. – Charles Duffy Aug 25 '20 at 19:21

0 Answers0