Use output of command as exit code

bashexit codegit

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?

Best Answer

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.

Related Question