How to delete local and remote git branch?
This blog will help you to delete a local git repository branch.
Local and remote branches are completely separate objects in git; deleting one wouldn’t delete the other, even if there is a tracking connections between them. So, if you have to delete both local and remote branches, delete them separately.
There are 3 different branches that need to be deleted in git:
- The local
- The remote
- The local remote-tracking branch
origin/<branch>that tracks the remote
Git delete a local branch
Note: You can not delete active branch, hence checkout another branch using below command first.
$ git checkout <other_branch_name>
-d option is an alias for
--delete, which only deletes the branch, if it has already been fully merged in its upstream branch. You could also use
-D, which is an alias for
--delete --force, which deletes the branch “irrespective of its merged status.”
$ git branch -d <branch_name_to_delete> # Syntex $ git branch -d issue-47 # Example - command to delete `issue-47` branch.
Force delete un-merged branches
$ git branch -D <branch_name_to_delete> # Syntex $ git branch -D issue-47 # Example - short for of force delete `issue-47` branch. $ git branch --delete --force issue-47 # Example - command to force delete `issue-47` branch.
Note: If the branch has a reflog, it will be deleted either.
--force flag in combination with
--delete), allows deleting the branch containing unmerged changes.
Note: Use the
-f flag very carefully, as it easily may cause data loss.
Git Delete remote branch
To delete a remote branch use
git push command with the
--delete flag as given below:
$ git push <remote_name> --delete <branch_name> ### In most of the case remote name will be `origin`, lets delete `issue-41` branch from remote `origin`. $ git push origin --delete issue-41
Git delete branch in versions older than 1.7.0
$ git push origin :<branch> # Syntex $ git push origin :issue-41 # Example
Delete a local remote-tracking branch
tracking branch in Git is a local branch that is connected to a remote branch. Following are the commands to delete local remote-tracking branch.
$ git branch --delete --remotes <remote>/<branch> $ git branch -dr <remote>/<branch> # Shorter $ git fetch <remote> --prune # Delete multiple obsolete tracking branches $ git fetch <remote> -p # Shorter