41

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?

Wes
  • 831

2 Answers2

34

You might be able to use curl's --fail option, though you should test it once first.

man curl

-f, --fail (HTTP) Fail silently (no output at all) on server errors. This is mostly done to better enable scripts etc to better deal with failed attempts. In normal cases when an HTTP server fails to deliver a document, it returns an HTML document stating so (which often also describes why and more). This flag will pre‐ vent curl from outputting that and return error 22.

          This method is not fail-safe and there are occasions where  non-
          successful  response  codes  will  slip through, especially when
          authentication is involved (response codes 401 and 407).

In this way you could just do:

args="-X POST -d@myfile.txt server-URL"
curl -f $args && echo "SUCCESS!" ||
    echo "OH NO!"
mikeserv
  • 58,310
  • This is probably the best practice in a scripting setting. For cURL exit codes see here: https://everything.curl.dev/usingcurl/returns – cyqsimon Apr 26 '21 at 11:23
28

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.

j--
  • 437