6

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?

1 Answer 1

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.

4
  • 4
    Use $(...) instead of backticks: much easier to see the difference. Commented Aug 14, 2017 at 14:59
  • 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
    Commented Aug 14, 2017 at 15:10
  • 1
    backticks are OK for bash, but bad for humans. It took me several seconds to spot the difference in your answer. Commented Aug 14, 2017 at 15:16
  • Backticks are also harder to nest.
    – Barmar
    Commented Aug 18, 2017 at 17:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .