Is there a better way to find out if a local git branch exists?

I am using the following command to find out if a local git branch with branch-name exists in my repository. Is this correct? Is there a better way?

Please note that I am doing this inside a script. For this reason I'd like to use plumbing commands if possible.

git show-ref --verify --quiet refs/heads/<branch-name>
# $? == 0 means local branch with <branch-name> exists. 

When I search for 'git check if branch exists' on a search engine, this page is the first one I see.

I get what I want, but I'd like to provide a updated answer since the original post was from 2011.

git rev-parse --verify <branch_name>

This is essentially the same as the accepted answer, but you don't need type in "refs/heads/"


As far as I know, that's the best way to do it in a script. I'm not sure there's much more to add to that, but there might as well be one answer that just says "That command does everything you want" :)

The only thing you might want to be careful of is that branch names can have surprising characters in them, so you may want to quote <branch-name>.


Almost there.

Just leave out the --verify and --quiet and you get either the hash if the branch exists or nothing if it doesn't.

Assign it to a variable and check for an empty string.

exists=`git show-ref refs/heads/<branch-name>`
if [ -n "$exists" ]; then
    echo 'branch exists!'
fi

I recommend git show-ref --quiet refs/heads/$name.

  • --quiet means there is no output, which is good because then you can cleanly check exit status.

  • refs/heads/$name limits to local branches and matches full names (otherwise dev would match develop)

Usage in a script:

if git show-ref --quiet refs/heads/develop; then
    echo develop branch exists
fi