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

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 

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
How to earn badges on the Atlassian Community

How to earn badges on the Atlassian Community

Badges are a great way to show off community activity, whether you’re a newbie or a Champion.

Learn more
Community showcase
Posted Jun 12, 2018 in Bitbucket

Do you use any Atlassian products for your personal projects?

After spinning my wheels trying to get organized enough to write a book for National Novel Writing Month (NaNoWriMo) I took my affinity for Atlassian products from my work life and decided to tr...

26,573 views 26 12
Join discussion

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