8

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.

0

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

3 Comments

that worked! Thank you, Inian, I really appreciate your help!
The suggested edit queue is full, but I'm sure many people are suggesting to change the part like < curl command > to be a little clearer since many people are reading the < and > symbols as part of the valuable code, but it is actually used here to show like this <curl command> | jq which is read very differently than < curl command > | jq.
@Urasquirrel: True, modified! thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.