T••LBX: Blog

Delete any Git branch the easy way

I don't know about you but each time I want to delete a remote branch in Git, I always end up looking online. For reference, here is the command:

$ git push <my-remote> :<my-branch>

Not the end of the world, but quite obscure to me because there is no reference to "branch" or "delete". And the worst is that it does look very different from the command to delete a local branch.

$ git branch -d <my-branch>

That one is acceptable, although I would still write an alias for it. But the thing is that I would like them to be similar. There are probably other ways to do this, maybe simpler ones, but here is the zshell function I ended up writing:

gbd() {
  if [[ $# == 0 ]] || [[ $1 == '-h' ]]; then
    echo 'Git branch delete'
    echo 'Usage local:  gbd <LOCAL_BRANCH>'
    echo 'Usage remote: gbd <REMOTE>/<BRANCH>'
    return 0
  local remote=${1:h}
  local branch=${1:t}
  if [[ $remote == '.' ]]; then
    echo "git branch -d $branch"
    git branch -d "$branch"
    echo "git push $remote :$branch"
    git push "$remote" ":$branch"

The name "gbd" stands for "git branch delete" which respects the order of words in a subcommand chain. That is to say from the least specific to the most specific. You can obviously pick another name. Now if you call the command without arguments or with -h, it will print the usage. And as the usage shows, you can either pass the name of a local branch, or remote and branch separated by a slash.

$ gbd newfeature
$ gbd staging/newfeature

The good thing with using a slash as a separator between remote and branch is that I can use Zshell path modifiers to isolate them.

Tags:     git shell zshell zsh