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

1
  • 3
    Given that your code is syntactically invalid, shellcheck.net should be your first recourse. Commented Jun 17, 2016 at 21:27

4 Answers 4

80

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';
Sign up to request clarification or add additional context in comments.

2 Comments

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.
As a one liner: [[ $(git rev-parse --abbrev-ref HEAD) == "master" ]] && echo "on master"
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

Comments

4

You want to use exit instead of return.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.