39

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
  • 90,741
  • 139
  • 482
  • 817
  • 3
    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

76

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
  • 246,190
  • 53
  • 318
  • 364
  • 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
  • 3,074
  • 1
  • 22
  • 28
4

You want to use exit instead of return.

jil
  • 2,601
  • 12
  • 14
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
  • 6,043
  • 3
  • 27
  • 39