Monday, June 24, 2019

Delete Branch in Git

How to Delete a Local and Remote Git Branch

When to delete branches: basically while we merge our branch code with main branch then there is no mean to keep branch. We should delete that branch which is not in use any more.

Some time we create branch but due to some reasons we are unable to merge the branch with main branch in this case also we should delete unused branch from local or remote.

Case-1: we have create branch work into it and the push and merge with remote main branch. This branch can be deleted easily so we can use simple git command to delete this.

// Delete local branch
git branch -d <branch_name>

// Delete remote branch
git push origin -d <remote_branch_name>

Case-2: we have create branch but code not pushed and merged with main branch and we want to delete this branch. At this time while you try to delete this branch. We will get error message like below.
error: The branch 'branch_name' is not fully merged.

If you are sure you want to delete it, run 'git branch -D branch_name'.
// Delete branch locally
git branch -D <branch_name>

// Delete branch remotely
git push origin --D <remote_branch_name>

If we try to delete the current branch, in which we are currently working. We will  get the following message:
error: Cannot delete branch 'branch_name' checked out at '/path/to/repository'
Note:- we cannot delete the branch where we are currently on. So if we want to delete currently working branch. First, we need to switch to another branch and then delete the branch

The -d option stands for (--delete): This is used to delete the branch only if it is already been pushed and merged with the remote branch.
Use -D option stands for --delete --force: if you want to force the branch to be deleted, even if it is not pushed or merged yet. So be careful using this one!

No comments:

Post a Comment