Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the current git branch in shell

Tags:

bash

shell

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?

like image 597
jdp Avatar asked Dec 10 '22 23:12

jdp


2 Answers

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
like image 148
William Pursell Avatar answered Jan 01 '23 14:01

William Pursell


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.

like image 27
statox Avatar answered Jan 01 '23 16:01

statox