0

I have a curl command which returns a json response as

{
"customer_id": "9a081c0c",
"resources": ["credit-98797", "credit-98798", "loan-876", "loan-889-approved","loan-882-rejected", "loan-879-pending"],
"customer_info": "John",
"warnings": null
}

I am trying to create a script which would return the latest loan id, in this case loan-889-approved But having hard time getting it right.

I tried sorting all the loans and fetching the first element of the array, but I am doing it wrong

details=$(curl -u username:token https://1.2.3.4:8420/v1/customer/details/9a081c0c)
sortedLoans=$(for x in ${details[@]}; do if [["$x"=="loan"]]; then echo $x; fi done | sort ) 

And the main challenge is to doing it using only bash, without jq or json, if possible

I am new to shell scripting. Any advice is appreciated. Thanks in advance

Pradeep
  • 91
  • 1
  • 4
  • 15
  • https://stackoverflow.com/a/61598788/874188 has an ambitious and portable shell-only solution. The source code should convince you that it's a dubious idea. – tripleee Nov 26 '20 at 13:48

1 Answers1

2

Since you mention you cannot use jq, try this solution with grep+sort+tail

curl '..' | grep -o 'loan-[^"]*' | sort -t- -k2n | tail -n1

sort -t- -k2n will sort numerically based on number that is present after -

Sundeep
  • 23,246
  • 2
  • 28
  • 103
  • Thanks a lot @Sundeep I will give it a try. I have missed a case where there will be text after the numerical values like `["credit-98797", "credit-98798", "loan-876", "loan-889-approved","loan-882-rejected", "loan-879-pending"]` and I would want to extract `loan-889-approved` My bad.. I edited it just now – Pradeep Nov 26 '20 at 13:41
  • This is hugely imprecise, and exactly the reason why you really should use JSON-capable tools like `jq` instead of an excessively quick and dirty hack which will stop working when you look away. – tripleee Nov 26 '20 at 13:42
  • @Pradeep I've edited, but as triplee mentions, this isn't robust – Sundeep Nov 26 '20 at 13:54
  • 1
    @Sundeep I completely understand. I did some reading on this and agree with triplee but unfortunately I have such a hard requirement, hence mentioned the same in the question too :( Thanks a ton for the response. Works like a charm.. you are a savior – Pradeep Nov 26 '20 at 14:05