Jenkinsfile

Disable trace messages (”+ some_command”) on console output

Issue:

When adding echo shell commands in a Jenkinsfile, like

script {
    sh '''
        echo "Hello world"
    '''
}

it causes the line to be printed twice, once as a execution trace messages, and once as the original echo command:

+ echo Hello world
Hello world

whereas we only want to second line to be shown.

Cause:

By default, Jenkins launches shell commands with the set -x option (see here for more info), which causes all commands to be echoed. For most commands defined inside the Jenkinsfile, that selection makes sense in order to know which command triggered the proceeding console output, but for echo it’s merely a repetition.

Solution:

Deactivate the trace printing by setting set +x (the “+” switches off the option), before executing the echo command. In case different commands follow in the same shell code block, re-activate it:

script {
    sh '''
        # ### Deactivate tracing
        { set +x; } 2>/dev/null
        echo "Hello world"
        # ### Re-activate tracing
        { set -x; } 2>/dev/null
        cp some_file /some/dir/
    '''
}

This shows the following console output:

Hello world
+ cp some_file /some/dir

In order to not show the set commands in the output, put them into curly braces assigning their stderr output to /dev/null:

{ set +x; } 2>/dev/null

Check current status of the pipeline

In order to check the current status of the pipeline within or in-between stages, use the following statement:

stage("Do something") {
    steps {
        echo "currentBuild.currentResult: ${currentBuild.currentResult}"
    }
}

You can also use the status as a conditional for execution of a stage:

stage('Do something if pipeline so far OK') {
    when {
        expression { currentBuild.currentResult == 'SUCCESS' }
    }
    steps {
        // do something
    }
}

Note

currentBuild.result returns null if used inside the stages section, but returns the status if used inside the post section.

Use time trigger as conditional

In case a certain step is only supposed to happen if a build was started via a time trigger, there is a conditional step, you can use:

if (env.BUILD_USER == "Timer Trigger") {
    // do something
}