Jenkins is written in Java and because of that it is a bit challenging to run things. Jenkins takes a shortcut and doesn’t actually run the commands you type into the build step of a job. Instead, Jenkins writes the build step into a temporary file and calls shell to run it.

If shell exits with code zero, Jenkins thinks everything went fine and the build gets a blue ball. Any other exit code means the build failed and gets a red ball.

Let’s look at an example.

#!/bin/sh make

echo “Build exit code was $?"

What is the exit code of the script above?

It will be zero, always. Why? Because the exit code of a script is the exit code of the last command and the echo command will succeed with very high probability.

So you see, it is up to you to not hide the exit code of your build from Jenkins.

Fortunately there is an easy way to do it. The shell has a convenient option -e, which causes shell to stop running a script immediately when any command exits with non-zero exit code. This makes it easy to have Jenkins know when your script fails.

By the way, there’s also one more useful shell option you might want to know about, -x, which makes shell print every command it executes.

Actually, Jenkins will run your build script using /bin/sh -xe, if you only let it. If you start your build script with #!/bin/sh, Jenkins will respect your wish and execute the script with /bin/sh with no options. If you omit the hash-bang line, Jenkins will fall back to /bin/sh -xe, which, you will probably now agree, is a good choice.

The discussion above was unfortunately bit specific to Unix. Sorry.