How to stop shell script if curl failed

26,862

Solution 1

You can check for exit code using $?:

exit_status = $?
if [ $exit_status != 0 ]
  then
    exit $exit_status
fi

If you want to analyze exit status, take a look at the Exit codes section from man curl page. There are a lot of different codes, depending on why it failed.

EDIT : You can use command1 || command2 as well. command2 is executed if and only if command1 has failed:

curl .... || exit 1

Solution 2

Just exit if curl ends with a non-zero exit code:

curl http://www.example.com || exit 1

Or, make your script exit on error:

set -e
curl http://www.example.com
Share:
26,862

Related videos on Youtube

Steelflax
Author by

Steelflax

Updated on September 18, 2022

Comments

  • Steelflax
    Steelflax over 1 year

    I have script that used curl when i pass wrong parameters to script curl failed but script continue executing. I have tried use curl -f/--fail parameter but problem does not solved. What is the best way to stop script?

    I have founded my mistake. I used curl command into another command

    echo `curl --fail ... || exit 1`
    

    After removing echo command curl become working properly. Thank you for answer, it is also useful.