Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I branch a shell script based on an HTTP status code from curl?

Tags:

bash

curl

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:

  • the script must continue running (if the return code is ok, like 200) or
  • the script must return a not ok status (if the return code is not ok, like 400) and end the script without doing anything

How can the return be read out from the curl ?? Simple script for most of you but ... ;-)

like image 843
nobody Avatar asked Dec 08 '22 23:12

nobody


1 Answers

The Problem

The curl program is shell-friendly, which means its exit status reflects the status of curl, not the HTTP status code.

The Solution

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')

Sample Output

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

Branching

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.

See Also

  • How can I get an HTTP status code with an AWK one-liner?
  • https://superuser.com/questions/272265/getting-curl-to-output-http-status-code
like image 139
Todd A. Jacobs Avatar answered Dec 22 '22 00:12

Todd A. Jacobs