Kworks
Kworks

Reputation: 793

How to purposely throw an Error in the shell script

I want to write a script which throws an error when the status of url is not equal to 200. As this script has to be executed on Jenkins so it should make the build fail.This is the script which i have written -

STATUS=$(curl -s -o /dev/null -w '%{http_code}' http://google.com)
  if [ $STATUS -eq 200 ]; then
    echo "URL is working fine"
    break
  else
    echo"URL is not working"
    cd 123
 fi

The above script works correctly but i need something else instead of -cd 123 syntax.

Upvotes: 3

Views: 10930

Answers (2)

sti
sti

Reputation: 11075

The easiest solution is to execute curl and use the -f option. It makes curl exit with non-zero exit code when web server returns something else than 200 OK.

You could also make your life easier by setting the -e option for shell. This causes shell to abort immediately when a command returns an error (= non-zero exit code).

So, your example above would be reduced to:

set -e
curl -sf -o /dev/null http://google.com
echo "URL is working fine"

Upvotes: 4

devnull
devnull

Reputation: 123508

but i need something else instead of -cd 123 syntax

You could say:

exit 42

instead. This would make the script exit with a non-zero exit code that should be picked up by Jenkins.

help exit tells:

exit: exit [n]
    Exit the shell.

    Exits the shell with a status of N.  If N is omitted, the exit status
    is that of the last command executed.

Upvotes: 7

Related Questions