Checkout specific Git branch or tag using it's name only

git Jan 20, 2016

For some compatibility reasons I needed to checkout specific branch or tag in the Git repository using only it's name (last part without refs/.../ prefix) from a bash script.

For Mercurial repositories it's not a problem at all thanks to:

hg checkout $tagOrBranch

I haven't found similar solution using git checkout, so as a workaround I've prepared the following bash script to do the job:

git fetch --all
if git show-ref | grep "refs/remotes/origin/$tagOrBranch"
    echo "It looks like a branch"
    git checkout -b $tagOrBranch
    git pull origin $tagOrBranch
    if git show-ref --tags | grep "refs/tags/$tagOrBranch\$"
        echo "It looks like a tag"
        git checkout tags/$branchOrTag
        echo "No branch / tag '$branchOrTag' found"
        exit 1


Mike Kowalski

Software Architect believing in craftsmanship and the power of fresh espresso. Writing in & about Java, distributed systems, and beyond. Tweeting as @mikemybytes. Mikes his own opinions and bytes.