5

I'm trying to write a shell script that should fail out if the current git branch doesn't match a pre-defined value.

if $gitBranch != 'my-branch'; then
   echo 'fail'
   exit 1
fi

Unfortunately, my shell scripting skills are not up to scratch: How do I get the current git branch in my variable?

Darek Kay
  • 15,827
  • 7
  • 64
  • 61
jdp
  • 3,446
  • 2
  • 30
  • 54
  • This may be a duplicate, but it's certainly not a duplicate of the question linked. – William Pursell May 26 '15 at 19:17
  • For the posterity, my suggested duplicate was: [How to compare strings in Bash script](http://stackoverflow.com/q/2237080/1983854), since it looks like the thing is missing here. – fedorqui May 26 '15 at 19:20

2 Answers2

13

To get the name of the current branch: git rev-parse --abbrev-ref HEAD

So, to check:

if test "$(git rev-parse --abbrev-ref HEAD)" != my-branch; then
  echo Current branch is not my-branch >&2
  exit 1
fi
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    Yup, although does anybody really use `test` rather than `[`? I would suggest `if [ "$(git rev-parse --abbrev-ref HEAD)" != 'my-branch' ] ;` – Mort May 26 '15 at 19:29
  • 1
    I may be the only one that prefers `test`, but I strongly suggest against `[`. The amount of confusion caused by people thinking that `[` is a part of the grammar of the shell is very high. Using `test` makes it much clearer that it is a command. And who wants to have a final argument of `]`? That's just weird. – William Pursell May 26 '15 at 19:58
  • Sure, it causes confusion -- but you only have to learn it once. – Keith Thompson May 26 '15 at 21:31
  • This fails in detached state. – Gerd K Oct 16 '17 at 22:18
1

You can get the branch using git branch and a regex:

$gitBranch=$(git branch | sed -n -e 's/^\* \(.*\)/\1/p')

After that you just have to make your test.

statox
  • 2,827
  • 1
  • 21
  • 41
  • 2
    The `sed` command can be written more simply as `sed -n '/^\* /s///p'`. – Keith Thompson May 26 '15 at 21:33
  • @Keith You're right. I got this snippet from somewhere on the internet and as it worked I never tried to improve it but your simplification totally works. – statox May 26 '15 at 21:36