Curl – How to Check if a Command Completed Without Error

curlerror handlinghttp

I am using curl to upload a file to a server via an HTTP post.

curl -X POST -d@myfile.txt server-URL

When I manually execute this command on the command line, I get a response from the server like "Upload successful". However, how if I want to execute this curl command via a script, how can I find out if my POST request was successful?

Best Answer

The simplest way is to store the response and compare it:

$ response=$(curl -X POST -d@myfile.txt server-URL);
$ if [ "Upload successful" == "${response}" ]; then … fi;

I haven't tested that. The syntax might be off, but that's the idea. I'm sure there are more sophisticated ways of doing it such as checking curl's exit code or something.

update

curl returns quite a few exit codes. I'm guessing a failed post might result in 55 Failed sending network data. So you could probably just make sure the exit code was zero by comparing to $? (Expands to the exit status of the most recently executed foreground pipeline.):

$ curl -X POST -d@myfile.txt server-URL;
$ if [ 0 -eq $? ]; then … fi;

Or if your command is relatively short and you want to do something when it fails, you could rely on the exit code as the condition in a conditional statement:

$ if curl --fail -X POST -d@myfile.txt server-URL; then
    # …(success)
else
    # …(failure)
fi;

I think this format is often preferred, but personally I find it less readable.

Related Question