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?

Sathyajith Bhat
  • 61,504
  • 38
  • 179
  • 264
Sven R.
  • 165
  • 5

1 Answers1

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.

Sathyajith Bhat
  • 61,504
  • 38
  • 179
  • 264
nKn
  • 5,549
  • 6
  • 32
  • 38
  • 4
    Use `$(...)` instead of backticks: much easier to see the difference. – glenn jackman Aug 14 '17 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 Aug 14 '17 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. – glenn jackman Aug 14 '17 at 15:16
  • Backticks are also harder to nest. – Barmar Aug 18 '17 at 17:49