How to Delete Branches in Git

Introduction

If there’s any commands I routinely forget, it is how to delete branches in Git. For the sake of drilling it into my brain I am writing this post on how to do so.

Deleting Locally

To delete a branch locally:

git branch -d <branch>

For example: git branch -d CRON-23

Important to note that Git will not let you delete a branch you are currently on, so you have to check out one that you are not deleting.

Also important to note that -d option deletes the branch only if it has already been pushed and merged with the remote branch. Otherwise, use -D to force the branch to be deleted, regardless if it has not been pushed or merged.

Deleting Remotely

To delete a branch remotely:

git push <remote> --delete <branch>

For example: git push origin --delete CRON-23

Alternatively, you can use the shorter: git push <remote> :<branch>

Synchronizing Branches

To keep your branch list synchronized with remote, use git fetch -p. The -p stands for prune. After fetch, branches that no longer exist on the remote will be deleted.

Conclusion

Deleting branches both locally and remotely only require simple one-line commands. However, for whatever reason (maybe they’re used less), they are easily forgotten! I know I will likely be referencing this post in the future.


Erik August Johnson is a software developer working with JavaScript to build useful things. Follow them on Twitter.