I am writing a bash script for a backup. The script is going to run a curl and this is going to return a certain code.
Depending on the result of this code:
How can the return be read out from the curl ?? Simple script for most of you but ... ;-)
The curl program is shell-friendly, which means its exit status reflects the status of curl, not the HTTP status code.
You can make a second call to the URL for a status code, use the write-out flag to append the status code to your output, or parse the headers. Here are some examples.
The first option is naive, in that you are making two separate calls, so the status code may not be the same between calls. Nevertheless, it could be useful in some cases.
# Make a second call to get the status code.
curl --verbose http://www.google.com 2>&1 |
sed -rn 's!^< HTTP/.* ([[:digit:]]+).*!\1!p'
The better way to do this is to append the status code to standard output, and then strip it out after you capture it. For example:
response=$(curl --silent --write-out "\n%{http_code}\n" http://google.com)
status_code=$(echo "$response" | sed -n '$p')
html=$(echo "$response" | sed '$d')
Using the example above, you can use these results any way you like. As one example, to view the HTML and the status code separately, you can do something like this:
$ echo "$html"; echo; echo "HTTP Status Code: $status_code"
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>301 Moved</TITLE></HEAD><BODY>
<H1>301 Moved</H1>
The document has moved
<A HREF="http://www.google.com/">here</A>.
</BODY></HTML>
HTTP Status Code: 301
Now that you have the status code, you can branch based on the value using an if/then or case statement. For example:
case "$status_code" in
200) echo 'Success!'
;;
*) echo 'Fail!'
exit 1
;;
esac
Note that you'll have to set your own exit status, and that you can't just re-use the HTTP status code. A shell exit status must be between 0-255, and many HTTP status codes are outside that range.
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