Issue
I have five cURL
statements that work fine by themselves and am trying to put them together in a bash script. Each cURL
statement relies on a variable generated from a cuRL
statement executed before it. I'm trying to figure out the smartest way to go about this. Here is the first cURL statement;
curl -i -k -b sessionid -X POST https://base/resource -H "Content-Type: application/json" -H "Authorization: Authorization: PS-Auth key=keyString; runas=userName; pwd=[password]" -d "{\"AssetName\":\"apiTest\",\"DnsName\":\"apiTest\",\"DomainName\":\"domainNameString\",\"IPAddress\":\"ipAddressHere\",\"AssetType\":\"apiTest\"}"
This works fine, it produces this output;
{"WorkgroupID":1,"AssetID":57,"AssetName":"apiTest","AssetType":"apiTest","DnsName":"apiTest","DomainName":"domainNameString","IPAddress":"ipAddressHere","MacAddress":null,"OperatingSystem":null,"LastUpdateDate":"2017-10-30T15:18:05.67-07:00"}
However, in the next cURL
statement, I need to use the integer from AssetID
in order to execute it. In short, how can I take the AssetID
value and store it to a variable to be used in the next statement? In total, I'll be using 5 cURL
statements and they rely on values generated in the preceeding statement to execute. Any insight on how is appreciated.
Solution
Download and install jq
which is like sed
for JSON
data. You can use it to slice and filter and map and transform structured data with the same ease that sed
, awk
, grep
does for unstructured data. Remember to replace '...'
with your actual curl
arguments
curl '...' | jq --raw-output '.AssetID'
and to store it in a variable use command-substitution syntax to run the command and return the result.
asset_ID=$( curl '...' | jq --raw-output '.AssetID' )
In the curl
command, drop the -i
flag to output only the JSON
data without the header information.
Answered By - Inian