33

I am very bad at shell scripting (with bash), I am looking for a way to check if the current git branch is "x", and abort the script if it is not "x".

    #!/usr/bin/env bash

    CURRENT_BRANCH="$(git branch)"
    if [[ "$CURRENT_BRANCH" -ne "master" ]]; then
          echo "Aborting script because you are not on the master branch."
          return;      # I need to abort here!
    fi

    echo "foo"

but this is not quite right

Alexander Mills
  • 78,517
  • 109
  • 412
  • 724
  • 2
    Given that your code is syntactically invalid, [shellcheck.net](http://shellcheck.net) should be your first recourse. – mklement0 Jun 17 '16 at 21:27

4 Answers4

66

Use git rev-parse --abbrev-ref HEAD to get the name of the current branch.

Then it's only a matter of simply comparing values in your script:

BRANCH="$(git rev-parse --abbrev-ref HEAD)"
if [[ "$BRANCH" != "x" ]]; then
  echo 'Aborting script';
  exit 1;
fi

echo 'Do stuff';
knittl
  • 216,605
  • 51
  • 293
  • 340
  • 3
    Side note: `git rev-parse --abbrev-ref HEAD` is the right way for this case, where you want to get something back (and not an error) for if HEAD is currently detached. To distinguish the detached HEAD case, use `git symbolic-ref HEAD` instead. – torek Jun 17 '16 at 21:34
  • 3
    As a one liner: `[[ $(git rev-parse --abbrev-ref HEAD) == "master" ]] && echo "on master"` – robenkleene Feb 14 '19 at 21:08
7

One option would be to parse the output of the git branch command:

BRANCH=$(git branch | sed -nr 's/\*\s(.*)/\1/p')

if [ -z $BRANCH ] || [ $BRANCH != "master" ]; then
    exit 1
fi

But a variant that uses git internal commands to get just the active branch name as suggested by @knittl is less error prone and preferable

Pankrates
  • 2,995
  • 1
  • 20
  • 28
4

You want to use exit instead of return.

jil
  • 2,428
  • 10
  • 13
0

With git 2 you can use a command easier to remember:

[[ $(git branch --show-current) == "master" ]] && echo "you are on master" || (echo "you are not on master"; echo "goodbye")

This is a one-liner version (notice the brackets on the last two commands to group them).

Gismo Ranas
  • 5,505
  • 3
  • 26
  • 32