Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to purposely throw an Error in the shell script

Tags:

shell

jenkins

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.

like image 979
Kworks Avatar asked Jan 17 '26 14:01

Kworks


2 Answers

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.
like image 88
devnull Avatar answered Jan 20 '26 10:01

devnull


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"
like image 26
sti Avatar answered Jan 20 '26 11:01

sti