Checkout specific Git branch or tag using its name only

#git Jan 19, 2016 1 min Mike Kowalski

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"
then
    echo "It looks like a branch"
    git checkout -b $tagOrBranch
    git pull origin $tagOrBranch
else
    if git show-ref --tags | grep "refs/tags/$tagOrBranch\$"
    then
        echo "It looks like a tag"
        git checkout tags/$branchOrTag
    else
        echo "No branch / tag '$branchOrTag' found"
        exit 1
    fi
fi

Mike Kowalski

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