58

I would like to mark a Jenkins build to fail on one scenario for example:

if [ -f "$file" ]
then
    echo "$file found."
else
    echo "$file not found."
    #Do Jenkins Build Fail
fi

Is it possible via Shell Script?

Answer: If we exit with integer 1, Jenkins build will be marked as failed. So I replaced the comment with exit 1 to resolve this.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Selvakumar Ponnusamy
  • 5,363
  • 7
  • 40
  • 78

3 Answers3

86

All you need to do is exit 1.

if [ -f "$file" ]
then
    echo "$file found."
else
    echo "$file not found."
    exit 1
fi
alk3ovation
  • 1,202
  • 11
  • 15
  • 3
    Could you add a link to the documentation that explains this? Thanks for the answer btw. – TyMayn Oct 30 '14 at 23:37
  • And it's possible set exit to another number for jenkins mark to another status type, i.e. unestable? – albertoiNET Mar 14 '17 at 13:17
  • 1
    @albertoiNET as far as I remember, any non-zero exit code will be interpreted by the shell as an error. However, the information is kept, so you can test which specific error code was returned. This is kind of the point of error codes in the first place. – Jonathan Benn Oct 05 '20 at 18:27
3

To fail a Jenkins build from .NET, you can use Environment.Exit(1).

Also, see How do I specify the exit code of a console application in .NET?.

Community
  • 1
  • 1
Ben
  • 54,723
  • 49
  • 178
  • 224
2

To fail a Jenkins build from Windows PowerShell, you can use Steve's tip for C# as follows:

$theReturnCode = 1
[System.Environment]::Exit( $theReturnCode )

Notes;

1.Windows recycles exit codes higher than 65535. ( https://stackoverflow.com/a/31881959/242110 )

2.The Jenkins REST API has a '/stop' command, but that will cancel the build instead of actually failing it. ( https://jenkinsapi.readthedocs.org/en/latest/build.html )

3.Jenkins can also mark a build 'unstable', and this post ( https://stackoverflow.com/a/8822743/242110 ) has details on that solution.

Community
  • 1
  • 1
AnneTheAgile
  • 9,932
  • 6
  • 52
  • 48