Delete Branch in Git – Remove a Local or Remote Branch

In Git, branches are used to manage different versions of a codebase. A branch is essentially a separate line of development, where changes can be made to the codebase without affecting the main branch. When a branch is no longer needed, it can be removed to keep the repository organized. In this article, we’ll cover how to remove a local or remote branch in Git.

Removing a Local Branch in Git

To remove a local branch in Git, follow these steps:

  1. Switch to another branch: Before removing a branch, make sure you’re not currently on that branch. If you are, switch to a different branch using the git checkout command.
ruby
$ git checkout master
  1. Delete the branch: Once you’re on a different branch, you can delete the local branch using the git branch command with the -d option. This will delete the branch if it has already been merged into the current branch.
ruby
$ git branch -d branch-name

If the branch has not been merged into the current branch, you can force delete the branch using the -D option.

ruby
$ git branch -D branch-name
  1. Confirm the branch has been removed: To confirm the branch has been removed, list all local branches using the git branch command.
ruby
$ git branch

Removing a Remote Branch in Git

To remove a remote branch in Git, follow these steps:

  1. List all remote branches: Before removing a remote branch, list all remote branches to confirm the name of the branch you want to remove.
ruby
$ git branch -r
  1. Delete the branch: To delete a remote branch, use the git push command with the --delete option, followed by the name of the remote branch.
perl
$ git push origin --delete branch-name
  1. Confirm the branch has been removed: To confirm the branch has been removed, list all remote branches again.
ruby
$ git branch -r

Conclusion

In Git, branches are used to manage different versions of a codebase. When a branch is no longer needed, it can be removed to keep the repository organized. To remove a local branch in Git, switch to a different branch and use the git branch command with the -d option. To remove a remote branch, use the git push command with the --delete option, followed by the name of the remote branch. It’s important to confirm that the branch has been removed using the appropriate git branch command.