Git - git-checkout Documentation (2024)

NAME

git-checkout - Switch branches or restore working tree files

SYNOPSIS

git checkout [-q] [-f] [-m] [<branch>]git checkout [-q] [-f] [-m] --detach [<branch>]git checkout [-q] [-f] [-m] [--detach] <commit>git checkout [-q] [-f] [-m] [[-b|-B|--orphan] <new_branch>] [<start_point>]git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>…​git checkout [<tree-ish>] [--] <pathspec>…​git checkout (-p|--patch) [<tree-ish>] [--] [<paths>…​]

DESCRIPTION

Updates files in the working tree to match the version in the indexor the specified tree. If no paths are given, git checkout willalso update HEAD to set the specified branch as the currentbranch.

git checkout <branch>

To prepare for working on <branch>, switch to it by updatingthe index and the files in the working tree, and by pointingHEAD at the branch. Local modifications to the files in theworking tree are kept, so that they can be committed to the<branch>.

If <branch> is not found but there does exist a tracking branch inexactly one remote (call it <remote>) with a matching name, treat asequivalent to

$ git checkout -b <branch> --track <remote>/<branch>

If the branch exists in multiple remotes and one of them is named bythe checkout.defaultRemote configuration variable, we’ll use thatone for the purposes of disambiguation, even if the <branch> isn’tunique across all remotes. Set it toe.g. checkout.defaultRemote=origin to always checkout remotebranches from there if <branch> is ambiguous but exists on theorigin remote. See also checkout.defaultRemote ingit-config[1].

You could omit <branch>, in which case the command degenerates to"check out the current branch", which is a glorified no-op withrather expensive side-effects to show only the tracking information,if exists, for the current branch.

git checkout -b|-B <new_branch> [<start point>]

Specifying -b causes a new branch to be created as ifgit-branch[1] were called and then checked out. Inthis case you can use the --track or --no-track options,which will be passed to git branch. As a convenience,--track without -b implies branch creation; see thedescription of --track below.

If -B is given, <new_branch> is created if it doesn’t exist; otherwise, itis reset. This is the transactional equivalent of

$ git branch -f <branch> [<start point>]$ git checkout <branch>

that is to say, the branch is not reset/created unless "git checkout" issuccessful.

git checkout --detach [<branch>]
git checkout [--detach] <commit>

Prepare to work on top of <commit>, by detaching HEAD at it(see "DETACHED HEAD" section), and updating the index and thefiles in the working tree. Local modifications to the filesin the working tree are kept, so that the resulting workingtree will be the state recorded in the commit plus the localmodifications.

When the <commit> argument is a branch name, the --detach option canbe used to detach HEAD at the tip of the branch (git checkout<branch> would check out that branch without detaching HEAD).

Omitting <branch> detaches HEAD at the tip of the current branch.

git checkout [<tree-ish>] [--] <pathspec>…​

Overwrite paths in the working tree by replacing with thecontents in the index or in the <tree-ish> (most often acommit). When a <tree-ish> is given, the paths thatmatch the <pathspec> are updated both in the index and inthe working tree.

The index may contain unmerged entries because of a previous failed merge.By default, if you try to check out such an entry from the index, thecheckout operation will fail and nothing will be checked out.Using -f will ignore these unmerged entries. The contents from aspecific side of the merge can be checked out of the index byusing --ours or --theirs. With -m, changes made to the working treefile can be discarded to re-create the original conflicted merge result.

git checkout (-p|--patch) [<tree-ish>] [--] [<pathspec>…​]

This is similar to the "check out paths to the working treefrom either the index or from a tree-ish" mode describedabove, but lets you use the interactive interface to showthe "diff" output and choose which hunks to use in theresult. See below for the description of --patch option.

OPTIONS

-q
--quiet

Quiet, suppress feedback messages.

--[no-]progress

Progress status is reported on the standard error streamby default when it is attached to a terminal, unless --quietis specified. This flag enables progress reporting even if notattached to a terminal, regardless of --quiet.

-f
--force

When switching branches, proceed even if the index or theworking tree differs from HEAD. This is used to throw awaylocal changes.

When checking out paths from the index, do not fail upon unmergedentries; instead, unmerged entries are ignored.

--ours
--theirs

When checking out paths from the index, check out stage #2(ours) or #3 (theirs) for unmerged paths.

Note that during git rebase and git pull --rebase, ours andtheirs may appear swapped; --ours gives the version from thebranch the changes are rebased onto, while --theirs gives theversion from the branch that holds your work that is being rebased.

This is because rebase is used in a workflow that treats thehistory at the remote as the shared canonical one, and treats thework done on the branch you are rebasing as the third-party work tobe integrated, and you are temporarily assuming the role of thekeeper of the canonical history during the rebase. As the keeper ofthe canonical history, you need to view the history from the remoteas ours (i.e. "our shared canonical history"), while what you didon your side branch as theirs (i.e. "one contributor’s work on topof it").

-b <new_branch>

Create a new branch named <new_branch> and start it at<start_point>; see git-branch[1] for details.

-B <new_branch>

Creates the branch <new_branch> and start it at <start_point>;if it already exists, then reset it to <start_point>. This isequivalent to running "git branch" with "-f"; seegit-branch[1] for details.

-t
--track

When creating a new branch, set up "upstream" configuration. See"--track" in git-branch[1] for details.

If no -b option is given, the name of the new branch will bederived from the remote-tracking branch, by looking at the local part ofthe refspec configured for the corresponding remote, and then strippingthe initial part up to the "*".This would tell us to use "hack" as the local branch when branchingoff of "origin/hack" (or "remotes/origin/hack", or even"refs/remotes/origin/hack"). If the given name has no slash, or the aboveguessing results in an empty name, the guessing is aborted. You canexplicitly give a name with -b in such a case.

--no-track

Do not set up "upstream" configuration, even if thebranch.autoSetupMerge configuration variable is true.

-l

Create the new branch’s reflog; see git-branch[1] fordetails.

--detach

Rather than checking out a branch to work on it, check out acommit for inspection and discardable experiments.This is the default behavior of "git checkout <commit>" when<commit> is not a branch name. See the "DETACHED HEAD" sectionbelow for details.

--orphan <new_branch>

Create a new orphan branch, named <new_branch>, started from<start_point> and switch to it. The first commit made on thisnew branch will have no parents and it will be the root of a newhistory totally disconnected from all the other branches andcommits.

The index and the working tree are adjusted as if you had previously run"git checkout <start_point>". This allows you to start a new historythat records a set of paths similar to <start_point> by easily running"git commit -a" to make the root commit.

This can be useful when you want to publish the tree from a commitwithout exposing its full history. You might want to do this to publishan open source branch of a project whose current tree is "clean", butwhose full history contains proprietary or otherwise encumbered bits ofcode.

If you want to start a disconnected history that records a set of pathsthat is totally different from the one of <start_point>, then you shouldclear the index and the working tree right after creating the orphanbranch by running "git rm -rf ." from the top level of the working tree.Afterwards you will be ready to prepare your new files, repopulating theworking tree, by copying them from elsewhere, extracting a tarball, etc.

--ignore-skip-worktree-bits

In sparse checkout mode, git checkout -- <paths> wouldupdate only entries matched by <paths> and sparse patternsin $GIT_DIR/info/sparse-checkout. This option ignoresthe sparse patterns and adds back any files in <paths>.

-m
--merge

When switching branches,if you have local modifications to one or more files thatare different between the current branch and the branch towhich you are switching, the command refuses to switchbranches in order to preserve your modifications in context.However, with this option, a three-way merge between the currentbranch, your working tree contents, and the new branchis done, and you will be on the new branch.

When a merge conflict happens, the index entries for conflictingpaths are left unmerged, and you need to resolve the conflictsand mark the resolved paths with git add (or git rm if the mergeshould result in deletion of the path).

When checking out paths from the index, this option lets you recreatethe conflicted merge in the specified paths.

--conflict=<style>

The same as --merge option above, but changes the way theconflicting hunks are presented, overriding themerge.conflictStyle configuration variable. Possible values are"merge" (default) and "diff3" (in addition to what is shown by"merge" style, shows the original contents).

-p
--patch

Interactively select hunks in the difference between the<tree-ish> (or the index, if unspecified) and the workingtree. The chosen hunks are then applied in reverse to theworking tree (and if a <tree-ish> was specified, the index).

This means that you can use git checkout -p to selectively discardedits from your current working tree. See the “Interactive Mode”section of git-add[1] to learn how to operate the --patch mode.

--ignore-other-worktrees

git checkout refuses when the wanted ref is already checkedout by another worktree. This option makes it check the refout anyway. In other words, the ref can be held by more than oneworktree.

--[no-]recurse-submodules

Using --recurse-submodules will update the content of all initializedsubmodules according to the commit recorded in the superproject. Iflocal modifications in a submodule would be overwritten the checkoutwill fail unless -f is used. If nothing (or --no-recurse-submodules)is used, the work trees of submodules will not be updated.Just like git-submodule[1], this will detach thesubmodules HEAD.

<branch>

Branch to checkout; if it refers to a branch (i.e., a name that,when prepended with "refs/heads/", is a valid ref), then thatbranch is checked out. Otherwise, if it refers to a validcommit, your HEAD becomes "detached" and you are no longer onany branch (see below for details).

You can use the "@{-N}" syntax to refer to the N-th lastbranch/commit checked out using "git checkout" operation. You mayalso specify - which is synonymous to "@{-1}.

As a special case, you may use "A...B" as a shortcut for themerge base of A and B if there is exactly one merge base. You canleave out at most one of A and B, in which case it defaults to HEAD.

<new_branch>

Name for the new branch.

<start_point>

The name of a commit at which to start the new branch; seegit-branch[1] for details. Defaults to HEAD.

<tree-ish>

Tree to checkout from (when paths are given). If not specified,the index will be used.

DETACHED HEAD

HEAD normally refers to a named branch (e.g. master). Meanwhile, eachbranch refers to a specific commit. Let’s look at a repo with threecommits, one of them tagged, and with branch master checked out:

 HEAD (refers to branch 'master') | va---b---c branch 'master' (refers to commit 'c') ^ | tag 'v2.0' (refers to commit 'b')

When a commit is created in this state, the branch is updated to refer tothe new commit. Specifically, git commit creates a new commit d, whoseparent is commit c, and then updates branch master to refer to newcommit d. HEAD still refers to branch master and so indirectly now refersto commit d:

$ edit; git add; git commit HEAD (refers to branch 'master')|va---b---c---d branch 'master' (refers to commit 'd') ^ | tag 'v2.0' (refers to commit 'b')

It is sometimes useful to be able to checkout a commit that is not atthe tip of any named branch, or even to create a new commit that is notreferenced by a named branch. Let’s look at what happens when wecheckout commit b (here we show two ways this may be done):

$ git checkout v2.0 # or$ git checkout master^^ HEAD (refers to commit 'b') | va---b---c---d branch 'master' (refers to commit 'd') ^ | tag 'v2.0' (refers to commit 'b')

Notice that regardless of which checkout command we use, HEAD now refersdirectly to commit b. This is known as being in detached HEAD state.It means simply that HEAD refers to a specific commit, as opposed toreferring to a named branch. Let’s see what happens when we create a commit:

$ edit; git add; git commit HEAD (refers to commit 'e') | v e /a---b---c---d branch 'master' (refers to commit 'd') ^ | tag 'v2.0' (refers to commit 'b')

There is now a new commit e, but it is referenced only by HEAD. We canof course add yet another commit in this state:

$ edit; git add; git commit 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 lookat what happens when we then checkout master:

$ git checkout master HEAD (refers to branch 'master') e---f | / va---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 commitf. Eventually commit f (and by extension commit e) will be deletedby the routine Git garbage collection process, unless we create a referencebefore 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 (1)$ git branch foo (2)$ git tag foo (3)
  1. creates a new branch foo, which refers to commit f, and thenupdates HEAD to refer to branch foo. In other words, we’ll no longerbe 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 objectname (typically by using git reflog), and then we can create a reference toit. For example, to see the last two commits to which HEAD referred, wecan 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. "gitcheckout abc"), and when the argument is both a valid <tree-ish>(e.g. a branch "abc" exists) and a valid <pathspec> (e.g. a fileor a directory whose name is "abc" exists), Git would usually askyou to disambiguate. Because checking out a branch is so common anoperation, however, "git checkout abc" takes "abc" as a <tree-ish>in such a situation. Use git checkout -- <pathspec> if you wantto checkout these paths out of the index.

EXAMPLES

  1. The following sequence checks out the master branch, revertsthe Makefile to two revisions back, deletes hello.c bymistake, and gets it back from the index.

    $ git checkout master (1)$ git checkout master~2 Makefile (2)$ rm -f hello.c$ git checkout hello.c (3)
    1. switch branch

    2. take a file out of another commit

    3. restore hello.c from the index

    If you want to check out all C source files out of the index,you can say

    $ git checkout -- '*.c'

    Note the quotes around *.c. The file hello.c will also bechecked out, even though it is no longer in the working tree,because the file globbing is used to match entries in the index(not in the working tree by the shell).

    If you have an unfortunate branch that is named hello.c, thisstep would be confused as an instruction to switch to that branch.You should instead write:

    $ git checkout -- hello.c
  2. After working in the wrong branch, switching to the correctbranch would be done using:

    $ git checkout mytopic

    However, your "wrong" branch and correct "mytopic" branch maydiffer in files that you have modified locally, in which casethe above checkout would fail like this:

    $ git checkout mytopicerror: You have local changes to 'frotz'; not switching branches.

    You can give the -m flag to the command, which would try athree-way merge:

    $ git checkout -m mytopicAuto-merging frotz

    After this three-way merge, the local modifications are notregistered in your index file, so git diff would show you whatchanges you made since the tip of the new branch.

  3. When a merge conflict happens during switching branches withthe -m option, you would see something like this:

    $ git checkout -m mytopicAuto-merging frotzERROR: Merge conflict in frotzfatal: merge program failed

    At this point, git diff shows the changes cleanly merged as inthe previous example, as well as the changes in the conflictedfiles. Edit and resolve the conflict and mark it resolved withgit add as usual:

    $ edit frotz$ git add frotz

GIT

Part of the git[1] suite

Git - git-checkout Documentation (2024)
Top Articles
What are Referral Codes? | Cello
ScotiaCard FAQs
Bank Of America Financial Center Irvington Photos
Tyler Sis 360 Louisiana Mo
Craigslist Home Health Care Jobs
Craigslist St. Paul
Skylar Vox Bra Size
My E Chart Elliot
Missed Connections Inland Empire
Kraziithegreat
Hawkeye 2021 123Movies
Klustron 9
Remnant Graveyard Elf
All Obituaries | Ashley's J H Williams & Sons, Inc. | Selma AL funeral home and cremation
A.e.a.o.n.m.s
Ave Bradley, Global SVP of design and creative director at Kimpton Hotels & Restaurants | Hospitality Interiors
WWE-Heldin Nikki A.S.H. verzückt Fans und Kollegen
Mills and Main Street Tour
Louisiana Sportsman Classifieds Guns
Moviesda3.Com
Pickswise Review 2024: Is Pickswise a Trusted Tipster?
Kringloopwinkel Second Sale Roosendaal - Leemstraat 4e
Vegito Clothes Xenoverse 2
Theater X Orange Heights Florida
Reborn Rich Kissasian
PCM.daily - Discussion Forum: Classique du Grand Duché
R&S Auto Lockridge Iowa
Hood County Buy Sell And Trade
Elbert County Swap Shop
The Creator Showtimes Near R/C Gateway Theater 8
8002905511
Miller Plonka Obituaries
Craigs List Jax Fl
Package Store Open Near Me Open Now
Martin Village Stm 16 & Imax
Craigslist Free Puppy
Rocksteady Steakhouse Menu
Wbli Playlist
Watchdocumentaries Gun Mayhem 2
Marine Forecast Sandy Hook To Manasquan Inlet
New York Rangers Hfboards
Craigslist Gigs Wichita Ks
Crazy Balls 3D Racing . Online Games . BrightestGames.com
How to Print Tables in R with Examples Using table()
Windshield Repair & Auto Glass Replacement in Texas| Safelite
Poe Self Chill
Dyi Urban Dictionary
Dineren en overnachten in Boutique Hotel The Church in Arnhem - Priya Loves Food & Travel
Heat Wave and Summer Temperature Data for Oklahoma City, Oklahoma
Bluebird Valuation Appraiser Login
Karen Kripas Obituary
Craigslist Farm And Garden Missoula
Latest Posts
Article information

Author: Jeremiah Abshire

Last Updated:

Views: 6491

Rating: 4.3 / 5 (74 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Jeremiah Abshire

Birthday: 1993-09-14

Address: Apt. 425 92748 Jannie Centers, Port Nikitaville, VT 82110

Phone: +8096210939894

Job: Lead Healthcare Manager

Hobby: Watching movies, Watching movies, Knapping, LARPing, Coffee roasting, Lacemaking, Gaming

Introduction: My name is Jeremiah Abshire, I am a outstanding, kind, clever, hilarious, curious, hilarious, outstanding person who loves writing and wants to share my knowledge and understanding with you.