How to Delete Branches in Git

Azhar Bashir Khan Feb 02, 2024
How to Delete Branches in Git

This tutorial will see about deleting branches, local and remote, in Git.

We create branches in Git to separate the development work (i.e.) we may create a branch for a feature, separate from the main branch.

Sometimes, we may decide to discard a branch and delete it from the repository in Git. The branch we want to delete could be present in the local or remote repository.

We will now illustrate this with an example.

Using git branch and git push to Delete Branches in Git

We usually create multiple branches in a Git repository in a typical development environment, apart from the main branch. We use the main branch for the final, production-level changes.

We may use one branch for feature development and the other for fixing bugs. Later, we would merge those branches into the release or the main branch when we want to release.

Sometimes, we may decide to delete some branches that are no longer needed. The branches may be present only in the local repository in Git, or they may also be present in the remote repository.

Suppose we have a branch named feature1 in the Git repository, a local branch. To delete a local branch in Git, we use the git branch command with the -d option.

The command’s syntax to delete the local branch is git branch -d <branch_name>. Thus, we use the following code to delete our local branch feature1.

$ git branch -d feature1

We can use the option -D and the command git branch, which is an alias for --delete --force options. This causes the deletion of the branch, even if it is not fully merged with its upstream branch.

Thus, we can do as follows.

$ git branch -D feature1

Sometimes, we may need to delete the remote branch as well. We may decide that we are done with a branch, which is no longer needed across the development team.

Thus, we may no longer keep that branch in the remote repository.

We can delete the remote branch using thegit push command with the --delete option.

The syntax of the command to delete remote branch is git push <remote_name> --delete <branch_name>.

Say, the branch feature1 is a remote branch. We can delete the remote branch as follows.

$ git push origin --delete feature1

Thus, we have elaborated on how to delete branches, local and remote, in Git.

Related Article - Git Branch

Related Article - Git Delete

Related Article - Git Push