Home Explore Blog CI



git

7th chunk of `Documentation/git-checkout.adoc`
141dfdfedd34e89188b5902799703164f84aa36cbe972cf10000000100000983
	 HEAD (refers to commit 'f')
	  |
	  v
      e---f
     /
a---b---c---d  branch 'master' (refers to commit 'd')
    ^
    |
  tag 'v2.0' (refers to commit 'b')
------------

In fact, we can perform all the normal Git operations. But, let's look
at what happens when we then checkout `master`:

------------
$ git checkout master

               HEAD (refers to branch 'master')
      e---f     |
     /          v
a---b---c---d  branch 'master' (refers to commit 'd')
    ^
    |
  tag 'v2.0' (refers to commit 'b')
------------

It is important to realize that at this point nothing refers to commit
`f`. Eventually commit `f` (and by extension commit `e`) will be deleted
by the routine Git garbage collection process, unless we create a reference
before that happens. If we have not yet moved away from commit `f`,
any of these will create a reference to it:

------------
$ git checkout -b foo  # or "git switch -c foo"  <1>
$ git branch foo                                 <2>
$ git tag foo                                    <3>
------------
<1> creates a new branch `foo`, which refers to commit `f`, and then
    updates `HEAD` to refer to branch `foo`. In other words, we'll no longer
    be in detached `HEAD` state after this command.
<2> similarly creates a new branch `foo`, which refers to commit `f`,
    but leaves `HEAD` detached.
<3> creates a new tag `foo`, which refers to commit `f`,
    leaving `HEAD` detached.

If we have moved away from commit `f`, then we must first recover its object
name (typically by using git reflog), and then we can create a reference to
it. For example, to see the last two commits to which `HEAD` referred, we
can use either of these commands:

------------
$ git reflog -2 HEAD # or
$ git log -g -2 HEAD
------------

ARGUMENT DISAMBIGUATION
-----------------------

When there is only one argument given and it is not `--` (e.g. `git
checkout abc`), and when the argument is both a valid _<tree-ish>_
(e.g. a branch `abc` exists) and a valid _<pathspec>_ (e.g. a file
or a directory whose name is "abc" exists), Git would usually ask
you to disambiguate.  Because checking out a branch is so common an
operation, however, `git checkout abc` takes "abc" as a _<tree-ish>_
in such a situation.  Use `git checkout -- <pathspec>` if you want
to checkout these paths out of the index.

EXAMPLES
--------

=== 1. Paths

The following sequence checks out the `master` branch, reverts
the

Title: Git Commit Reference and Checkout
Summary
When switching from a detached HEAD state to a branch, commits without a reference are subject to garbage collection, but can be preserved by creating a new branch, tag, or reference, and Git provides options to recover and manage such commits, as well as to disambiguate between tree-ish and pathspec arguments during checkout operations.