In Bitbucket Pipelines, why doesn't '$?' get the expected exit code from the previously run command?

Paul Watson Atlassian Team Jul 21, 2017

In a script I have:

script:

  - set +e  # turn off error-trapping

  - failing-tests

  - echo $?

I expect an exit code of 1, but get 0. What's going on?

2 answers

This widget could not be displayed.

Pipelines executes the printf command before every command in a script section of the bitbucket-pipelines.yml file in order to print those commands to the logs. This means, for example, that:

script:

  - mvn clean build

 

actually behave like this:

script:

  - printf "+ mvn clean build\n"

  - mvn clean build

 

One consequence of this is that an attempt to use '$?' to pass the exit code of a failing command to the next command (when error-trapping is turned off) will fail because the next command actually receives the exit code of the printf command.

For example:

script:

  - set +e  # turn off error-trapping

  - failing-tests

  - echo $?

 

will behave like this:

script:

  - printf "set +e\n"

  - set +e  # turn off error-trapping

  - printf "failing-tests\n"

  - failing-tests

  - printf "echo $?\n"

  - echo $?  # with exit code of 0, because the preceding printf command succeeded

 

If you want to catch the exit code of a failing command, a workaround is to combine commands on the same line (to prevent the printf command from intercepting the exit code), like this:

script:

  - set +e

  - failing-tests; echo $? # with exit code of 1 in this case 
This widget could not be displayed.

Do it like this instead: 


- step:
  name: notify
  image: cfcommunity/slack-notification-resource
  script:
- |
set +e
faiing-tests
echo $?
- some other stuff
- yet more stuff

    

Suggest an answer

Log in or Sign up to answer
Community showcase
Published Aug 21, 2018 in Bitbucket

Branch Management with Bitbucket

As a project manager, I have discovered that different developers want to bring their previous branching method with them when they join the team. Some developers are used to performing individual wo...

1,199 views 8 10
Read article

Atlassian User Groups

Connect with like-minded Atlassian users at free events near you!

Find a group

Connect with like-minded Atlassian users at free events near you!

Find my local user group

Unfortunately there are no AUG chapters near you at the moment.

Start an AUG

You're one step closer to meeting fellow Atlassian users at your local meet up. Learn more about AUGs

Groups near you