Use output of command as exit code

6

0

For my Continuous Integration scripts I want to check if the git branch is not in sync with the master branch. Therefore I use

git rev-list --left-right --count master...my-branch-name

It will return sth. like

1    3

(3 commits ahead of master, 1 behind)

Adding | cut -f1 will give me only the first number (commits behind master).

Now I want to exit the script just with that number because 0 commits behind is success, all other should give an error.

How can I do that? I tried

exit 'git rev-list --left-right --count master...my-branch-name | cut -f1'

but this raises

/bin/bash: line 66: exit: git rev-list --left-right --count master...my-branch-name | cut -f1: numeric argument required

Is there a best practice for this?

Sven R.

Posted 2017-08-14T14:17:44.410

Reputation: 165

Answers

5

Simply change your line:

exit 'git rev-list --left-right --count master...my-branch-name | cut -f1'

to:

exit `git rev-list --left-right --count master...my-branch-name | cut -f1`

Anything between the ` quotation marks will be executed and returned to the bash script, so you can do whatever you want with it, including assigning it to a variable.

nKn

Posted 2017-08-14T14:17:44.410

Reputation: 4 960

4Use $(...) instead of backticks: much easier to see the difference. – glenn jackman – 2017-08-14T14:59:46.823

Possibly yes, the way I wrote is the historical compatibility way of doing it, the $(...) way is newer and supposedly more "compatible" between different shells, but both should work with no issues in bash. – nKn – 2017-08-14T15:10:53.293

1backticks are OK for bash, but bad for humans. It took me several seconds to spot the difference in your answer. – glenn jackman – 2017-08-14T15:16:24.110

Backticks are also harder to nest. – Barmar – 2017-08-18T17:49:54.287