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.
To get JSON with Curl, you need to make an HTTP GET request and provide the Accept: application/json request header. The application/json request header is passed to the server with the curl -H command-line option and tells the server that the client is expecting JSON in response.
For those of you want to copy the cURL output in the clipboard instead of outputting to a file, you can use pbcopy by using the pipe | after the cURL command. Example: curl https://www.google.com/robots.txt | pbcopy . This will copy all the content from the given URL to your clipboard.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With