1

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

1
  • 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. Commented Nov 26, 2020 at 13:48

1 Answer 1

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 -

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

4 Comments

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
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.
@Pradeep I've edited, but as triplee mentions, this isn't robust
@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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.