'What precisely happens when deleting a branch in Git

I have been looking for an answer to this question for a while now, but am still not entirely sure about its answer. Most information I found about deleting branches was no more than a copy of what the manual says (for example here on SO). I think a core problem is that I do not know precisely what a branch in Git is (even though there are many articles that claim to explain that). The only somewhat useful information I found was in this SO answer and the docs installed with git.

My question:

When I run git branch -d BRANCH_NAME,

  1. what happens under the hood?
  2. what changes externally, i.e. how does my interaction with the repository change?
  3. can any of these changes be considered a change in the history?

and additionally the same subquestions for git branch -D BRANCH_NAME.

My current understanding:

First my perception of a branch: depending on the context, the term branch refers to either a pointer to a certain commit (strictly called the branch head), or the list of commits leading up to that

What I think happens (but am quite unsure about), for git branch -d BRANCH_NAME:

  1. the pointer to the branch head is removed, and no more
  2. I can't see the branch in any listing anymore and I cannot switch to it or branch from it anymore (although I guess I could create a new branch at that commit, to effectively achieve those things)
  3. probably not: the commits are still there, they are only not labeled with the name of the branch anymore?

What I think happens, for git branch -D BRANCH_NAME:

  1. the pointer to the branch head is removed, and any commits that are not on an other branch as well are deleted
  2. I can't see the branch in any listing anymore and I cannot switch to it or branch from it anymore, or retrieve the code in any way
  3. yes: the commits in the branch are lost


Solution 1:[1]

The commits are still there after branch removal, until the next garbage collection. git branch -d (and -D) print the abbreviated commit hash, you can use it as the argument to git log or git checkout or git branch, which gives you the possibility to restore the deleted branch.

The only difference between -d and -D is that git branch -d will not let you delete unmerged branch (i.e. potentially lose commits).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sergej Koščejev