Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the parent of a Git commit? How can there be more than one parent to a Git commit? [duplicate]

Tags:

git

I was looking at this question when I got really confused. My understanding was that the previous commit is the parent of a commit.

like image 229
Rat Salad Avatar asked Jul 07 '16 07:07

Rat Salad


People also ask

Can a git commit have multiple parents?

Commits in git can have multiple parents, aka 'merge commits'. Using them maintains the branch history. They don't maintain the branch name, or even the history of the branch: they just tell what are the parent commits of the commit; as mentioned above, this history can be a "lie".

What is parent 1 and parent 2 in git?

Every commit in git has at least one parent (except for the first/initial commit). A commit's parent is the previous one. C1 is the initial commit. C2 is the second one.

Why merge commit has 2 parents?

A commit can have 2 parents, which is the result of merging one branch to another in the way of "true merge". A commit can have more than 2 parents, which is the result of merging 2 or more branches to one branch at the same time, in the way of "octopus merge".


1 Answers

The parent commit is the commit this current commit is based on. Usually:

  • When you git commit normally, the current commit becomes the parent commit of the new commit that's introduced by the command.
  • When you git merge two commits (or branches, whatever) without fast-forwarding, a new commit will be created with both commits as parents. You can merge more than two commits in that way, so the new commit may have more than one parent.

Essentially, the commit tree (or DAG, if we want to be accurate) is made up of those parent<-child relationships, with the children (more "recent"[1] commits) point to the parents (less "recent"[1] commits).

The only exception is the initial commit (or any other root commits), which has no parents.


  1. "recent" isn't exactly an accurate term, as you may have a very old branch on the one hand, and a very new one on the other. And a child commit may be a lot "older" than another commit which is a parent elsewhere.
like image 198
Madara's Ghost Avatar answered Sep 21 '22 06:09

Madara's Ghost