Do manual build fail in Jenkins using shell script

ShellJenkinsContinuous Integration

Shell Problem Overview


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.

Shell Solutions


Solution 1 - Shell

All you need to do is exit 1.

if [ -f "$file" ]
then
    echo "$file found."
else
    echo "$file not found."
    exit 1
fi

Solution 2 - Shell

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

Also, see https://stackoverflow.com/questions/155610/how-do-i-specify-the-exit-code-of-a-console-application-in-net.

Solution 3 - Shell

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSelvakumar PonnusamyView Question on Stackoverflow
Solution 1 - Shellalk3ovationView Answer on Stackoverflow
Solution 2 - ShellBenView Answer on Stackoverflow
Solution 3 - ShellAnneTheAgileView Answer on Stackoverflow