O'Reilly logo

Version Control with Git by Jon Loeliger

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Deleting Branches

The command git branch -d branch removes the named branch from a repository. Git prevents you from removing the current branch:

$ git branch -d bug/pr-3
error: Cannot delete the branch 'bug/pr-3' which you are currently on.

Removing the current branch would leave Git unable to determine what the resulting working directory tree should look like. Instead, you must always name a noncurrent branch.

But there is another subtle issue. Git won’t allow you to delete a branch that contains commits that are not also present on the current branch. That is, Git prevents you from accidentally removing development in commits that will be lost if the branch were to be deleted.

$ git checkout master
Switched to branch "master"

$ git branch -d bug/pr-3
error: The branch 'bug/pr-3' is not an ancestor of your current HEAD.
If you are sure you want to delete it, run 'git branch -D bug/pr-3'.

In this git show-branch output, the commit Added a bug fix for pr-3 is found only on the bug/pr-3 branch. If that branch were to be deleted, there would no longer be a way to access that commit.

By stating that the bug/pr-3 branch is not an ancestor of your current HEAD, Git is telling you that the line of development represented by the bug/pr-3 branch does not contribute to the development of the current branch, master.

Git is not mandating that all branches be merged into the master branch before they can be deleted. Remember, a branch is simply a name or pointer to a commit that has actual content. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required