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?

2
  • This may be a duplicate, but it's certainly not a duplicate of the question linked. Commented May 26, 2015 at 19:17
  • For the posterity, my suggested duplicate was: How to compare strings in Bash script, since it looks like the thing is missing here. Commented May 26, 2015 at 19:20

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

Yup, although does anybody really use test rather than [? I would suggest if [ "$(git rev-parse --abbrev-ref HEAD)" != 'my-branch' ] ;
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.
Sure, it causes confusion -- but you only have to learn it once.
This fails in detached state.
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.

2 Comments

The sed command can be written more simply as sed -n '/^\* /s///p'.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.