Skip to content

Instantly share code, notes, and snippets.

@StevenACoffman
Last active February 14, 2017 19:51
Show Gist options
  • Save StevenACoffman/86e80aab528b2f172f47b8da2966e950 to your computer and use it in GitHub Desktop.
Save StevenACoffman/86e80aab528b2f172f47b8da2966e950 to your computer and use it in GitHub Desktop.
Safe Alternative to curl | jq that will not bomb out if json is not returned
#!/bin/bash
# call this with normal curl arguments, especially url argument, e.g.
# safecurl.sh "http://example.com:8080/something/"
# separating the (verbose) curl options into an array for readability
curl_args=(
-H 'Accept:application/json'
-H 'Content-Type:application/json'
--write '\n%{http_code}\n'
--fail
--silent
)
echo "${curl_args[@]}"
# prepend some arguments, but pass on whatever arguments this script was called with
output=$(curl "${curl_args[@]}" "$@")
return_code=$?
if [ 0 -eq $return_code ]; then
# remove the "http_code" line from the end of the output, and parse it
echo "$output" | sed '$d' | jq .
else
# echo to stderr so further piping to jq will process empty output
>&2 echo "Failure: code=$output"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment