Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

git checkout <commit-hash> vs git checkout branch

I was playing around with git and got confused here.

The HEAD of develop branch is at
235a6d8

When I do:

git checkout 235a6d8

from any other branch or from develop branch, this leaves me in detached head.
I am not sure why does this happen when I am checking out to the latest commit on this branch.

When I do:

git checkout develop

I can switch to develop branch correctly.

I am not getting the difference between git checkout <commit-has> and git checkout branchname.
How they are different ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A git checkout <commit-hash>, Prepare to work on top of <commit>, by detaching HEAD at it (see "DETACHED HEAD" section), and updating the index and the files in the working tree.

While a git checkout <branch> does a switch: it prepares for working on <branch>, switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch.

This is confusing.

Mark Longair documented that confusion in "Why is the git command to switch branches named “git checkout”?"

He also wrote in May 2012: "The most confusing git terminology":

In CVS and Subversion “checkout” creates a new local copy of the source code that is linked to that repository.
The closest command in Git is “git clone”.
However, in git, “git checkout” is used for something completely distinct.
In fact, it has two largely distinct modes of operation:

  • To switch HEAD to point to a new branch or commit, in the usage git checkout <branch>. If <branch> is genuinely a local branch, this will switch to that branch (i.e. HEAD will point to the ref name) or if it otherwise resolves to a commit will detach HEAD and point it directly to the commit’s object name.
  • To replace a file or multiple files in the working copy and the index with their content from a particular commit or the index.
    This is seen in the usages: git checkout -- (update from the index) and git checkout <tree-ish> -- (where <tree-ish> is typically a commit).

In my ideal world, these two modes of operation would have different verbs, and neither of them would be “checkout.

Well... That is why Git 2.23 (Q3 2019) will split checkout into:

  • git restore which updates the working tree (and possibly the index)
  • git switch which can switch branches, or detach one if requested, in order for all new commits to be added to the tip of this branch.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...