Pipelines builds succeeds even on command failure
Platform Notice: Cloud - This article applies to Atlassian products on the cloud platform.
Summary
Pipelines build step status is considered successful, even if a command during the build execution returns a non-zero exit code.
OR
There's a need to have pipelines return success even if a non-zero exit code is returned.
Environment
Bitbucket Pipelines. This can be reproduced both on Pipelines Runners or Bitbucket Cloud Pipelines.
Scenario 1: For bash piped commands
Diagnosis
The bitbucket pipeline script contains multiple commands connected with a bash pipe ( for example command1 | command2
) , and the build step status is considered successful even if one of the piped commands fails (returns a non-zero exit code).
Cause
By default in some shells, including bash - the shell used by Bitbucket Pipelines - when two or mode commands are piped like :
command1 | command 2
The exit status taken into consideration is the exit status of the last command in that pipeline, unless the pipefail option is enabled. So in the example above, the Bitbucket pipeline build step would just be considered as Failed if command2
failed, returning a non-zero exit code, regardless if command1
was successful or not.
Solution
The shell's pipefail option can be enabled in order for bash to consider the exit status of all the commands in a pipeline by adding the following instruction in the build's script :
set -o pipefail
Upon setting this option, for the commands executed after it , the pipeline’s return status is the value of the last (rightmost) command to exit with a non-zero status or zero if all commands exit successfully.
Scenario 2: For all the commands
Diagnosis
When any Bitbucket Pipelines build starts, this is the default setting:
set -e
This setting in some shells, in this case bash, allows the build to immediately stop execution if any of the commands during the shell session return a non-zero exit code. For more details about this flag please refer to its manual page.
When this flag is set to +e, Pipelines is unable to identify whether the build is successful or not.
Cause
If the command below is executed at any point during the build, it will change the default shell behavior, making the build not exit when a non-zero exit code is returned by a command, effectively making Pipelines not exit when a non-zero exit code is returned. This will force the build to finish with a successful status:
set +e
Solution
To change the shell's behavior with command fails, one of the following commands needs to be included in the build script accordingly to the desired outcome:
- Do not want the step to stop at first command failure:
set +e # Do not stop builds at first command failure
OR
- Want the build to stop at first command failure:
set -e # Stop builds at first command failure