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

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


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

Tags:

Shell

Git

Bash

Sh