0

I'm using curl to send some json data. Part of the data is a request counter that needs to be incremented after each call.

I would like to reduce the code below by incrementing it right after evaluating it. I'm not sure how to format the variable within the json string though.

Thank you in advance!

#!/bin/bash
reqcnt=0
curl http://myurl.com --data-binary '{"requestCounter":'${reqcnt}'}'
((reqcnt++))

Expected:

#!/bin/bash
reqcnt=0
curl http://myurl.com --data-binary '{"requestCounter":'${((reqcnt++)}'}'

Edit

Taking into account the great answer by Inian, I noticed there are cases where I need to save the output of curl. For some reason the arithmetic operation is not performed on the variable in that case:

res=$(curl http://myurl.com --data-binary {"requestCounter":'"$((reqcnt++))"'}')
tzippy
  • 6,458
  • 30
  • 82
  • 151
  • 1
    The operation is performed, but on a copy of `reqcnt` because the increment takes place in a subshell. You'll see that if you add `echo $reqcnt` at the end of the command substitution. To update the value in the parent shell, you have to increment separately, outside of the command substitution. – Benjamin W. Jan 02 '19 at 17:26
  • Do you need the updated value of `reqcnt` to persist *between* runs of the script, or are you just showing a small part of a larger script? If the former, syntax is the least of your problems. – chepner Jan 02 '19 at 20:10
  • @BenjaminW. Okay, thanks, now I seem to understand the concept of subshells a little more! – tzippy Jan 03 '19 at 08:33
  • @chepner No this is actually just a snippet from a bigger script – tzippy Jan 03 '19 at 08:35

0 Answers0