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 … 😉
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.
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:
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:
Branching
Now that you have the status code, you can branch based on the value using an if/then or case statement. For example:
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