'bash script to check if the current git branch = "x"

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



Solution 1:[1]

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';

Solution 2:[2]

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

Solution 3:[3]

You want to use exit instead of return.

Solution 4:[4]

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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Pankrates
Solution 3 jil
Solution 4 Gismo Ranas