Movatterモバイル変換


[0]ホーム

URL:


Git
English ▾Topics ▾ Latest version ▾git-worktree last updated in 2.52.0

NAME

git-worktree - Manage multiple working trees

SYNOPSIS

gitworktreeadd [-f] [--detach] [--checkout] [--lock [--reason<string>]] [--orphan] [(-b |-B)<new-branch>]<path> [<commit-ish>]gitworktreelist [-v |--porcelain [-z]]gitworktreelock [--reason<string>]<worktree>gitworktreemove<worktree><new-path>gitworktreeprune [-n] [-v] [--expire<expire>]gitworktreeremove [-f]<worktree>gitworktreerepair [<path>…​]gitworktreeunlock<worktree>

DESCRIPTION

Manage multiple working trees attached to the same repository.

A git repository can support multiple working trees, allowing you to checkout more than one branch at a time. Withgitworktreeadd a new workingtree is associated with the repository, along with additional metadatathat differentiates that working tree from others in the same repository.The working tree, along with this metadata, is called a "worktree".

This new worktree is called a "linked worktree" as opposed to the "mainworktree" prepared bygit-init[1] orgit-clone[1].A repository has one main worktree (if it’s not a bare repository) andzero or more linked worktrees. When you are done with a linked worktree,remove it withgitworktreeremove.

In its simplest form,gitworktreeadd<path> automatically creates anew branch whose name is the final component of<path>, which isconvenient if you plan to work on a new topic. For instance,gitworktreeadd../hotfix creates new branchhotfix and checks it out atpath../hotfix. To instead work on an existing branch in a new worktree,usegitworktreeadd<path><branch>. On the other hand, if you justplan to make some experimental changes or do testing without disturbingexisting development, it is often convenient to create athrowawayworktree not associated with any branch. For instance,gitworktreeadd-d<path> creates a new worktree with a detachedHEADat the same commit as the current branch.

If a working tree is deleted without usinggitworktreeremove, thenits associated administrative files, which reside in the repository(see "DETAILS" below), will eventually be removed automatically (seegc.worktreePruneExpire ingit-config[1]), or you can rungitworktreeprune in the main or any linked worktree to clean up anystale administrative files.

If the working tree for a linked worktree is stored on a portable deviceor network share which is not always mounted, you can prevent itsadministrative files from being pruned by issuing thegitworktreelockcommand, optionally specifying--reason to explain why the worktree islocked.

COMMANDS

add<path> [<commit-ish>]

Create a worktree at<path> and checkout<commit-ish> into it. The new worktreeis linked to the current repository, sharing everything except per-worktreefiles such asHEAD,index, etc. As a convenience,<commit-ish> maybe a bare "-", which is synonymous with@{-1}.

If<commit-ish> is a branch name (call it<branch>) and is not found,and neither-b nor-B nor--detach are used, but there doesexist a tracking branch in exactly one remote (call it<remote>)with a matching name, treat as equivalent to:

$ git worktree add --track -b<branch> <path> <remote>/<branch>

If the branch exists in multiple remotes and one of them is named bythecheckout.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 alsocheckout.defaultRemote ingit-config[1].

If<commit-ish> is omitted and neither-b nor-B nor--detach used,then, as a convenience, the new worktree is associated with a branch (callit<branch>) named after$(basename<path>). If<branch> doesn’texist, a new branch based onHEAD is automatically created as if-b<branch> was given. If<branch> does exist, it will be checked outin the new worktree, if it’s not checked out anywhere else, otherwise thecommand will refuse to create the worktree (unless--force is used).

If<commit-ish> is omitted, neither--detach, or--orphan isused, and there are no valid local branches (or remote branches if--guess-remote is specified) then, as a convenience, the new worktree isassociated with a new unborn branch named<branch> (after$(basename<path>) if neither-b or-B is used) as if--orphan waspassed to the command. In the event the repository has a remote and--guess-remote is used, but no remote or local branches exist, then thecommand fails with a warning reminding the user to fetch from their remotefirst (or override by using-f/--force).

list

List details of each worktree. The main worktree is listed first,followed by each of the linked worktrees. The output details includewhether the worktree is bare, the revision currently checked out, thebranch currently checked out (or "detached HEAD" if none), "locked" ifthe worktree is locked, "prunable" if the worktree can be pruned by theprune command.

lock

If a worktree is on a portable device or network share which is not alwaysmounted, lock it to prevent its administrative files from being prunedautomatically. This also prevents it from being moved or deleted.Optionally, specify a reason for the lock with--reason.

move

Move a worktree to a new location. Note that the main worktree or linkedworktrees containing submodules cannot be moved with this command. (Thegitworktreerepair command, however, can reestablish the connectionwith linked worktrees if you move the main worktree manually.)

prune

Prune worktree information in$GIT_DIR/worktrees.

remove

Remove a worktree. Only clean worktrees (no untracked files and nomodification in tracked files) can be removed. Unclean worktrees or oneswith submodules can be removed with--force. The main worktree cannot beremoved.

repair [<path>...]

Repair worktree administrative files, if possible, if they have becomecorrupted or outdated due to external factors.

For instance, if the main worktree (or bare repository) is moved, linkedworktrees will be unable to locate it. Runningrepair in the mainworktree will reestablish the connection from linked worktrees back to themain worktree.

Similarly, if the working tree for a linked worktree is moved withoutusinggitworktreemove, the main worktree (or bare repository) will beunable to locate it. Runningrepair within the recently-moved worktreewill reestablish the connection. If multiple linked worktrees are moved,runningrepair from any worktree with each tree’s new<path> as anargument, will reestablish the connection to all the specified paths.

If both the main worktree and linked worktrees have been moved or copied manually,then runningrepair in the main worktree and specifying the new<path>of each linked worktree will reestablish all connections in bothdirections.

unlock

Unlock a worktree, allowing it to be pruned, moved or deleted.

OPTIONS

-f
--force

By default,add refuses to create a new worktree when<commit-ish> is a branch name and is already checked out byanother worktree, or if<path> is already assigned to someworktree but is missing (for instance, if<path> was deletedmanually). This option overrides these safeguards. To add a missing butlocked worktree path, specify--force twice.

move refuses to move a locked worktree unless--force is specifiedtwice. If the destination is already assigned to some other worktree but ismissing (for instance, if<new-path> was deleted manually), then--forceallows the move to proceed; use--force twice if the destination is locked.

remove refuses to remove an unclean worktree unless--force is used.To remove a locked worktree, specify--force twice.

-b<new-branch>
-B<new-branch>

Withadd, create a new branch named<new-branch> starting at<commit-ish>, and check out<new-branch> into the new worktree.If<commit-ish> is omitted, it defaults toHEAD.By default,-b refuses to create a new branch if it alreadyexists.-B overrides this safeguard, resetting<new-branch> to<commit-ish>.

-d
--detach

Withadd, detachHEAD in the new worktree. See "DETACHED HEAD"ingit-checkout[1].

--checkout
--no-checkout

By default,add checks out<commit-ish>, however,--no-checkout canbe used to suppress checkout in order to make customizations,such as configuring sparse-checkout. See "Sparse checkout"ingit-read-tree[1].

--guess-remote
--no-guess-remote

Withworktreeadd<path>, without<commit-ish>, insteadof creating a new branch fromHEAD, if there exists a trackingbranch in exactly one remote matching the basename of<path>,base the new branch on the remote-tracking branch, and markthe remote-tracking branch as "upstream" from the new branch.

This can also be set up as the default behaviour by using theworktree.guessRemote config option.

--relative-paths
--no-relative-paths

Link worktrees using relative paths or absolute paths (default).Overrides theworktree.useRelativePaths config option, seegit-config[1].

Withrepair, the linking files will be updated if there’s an absolute/relativemismatch, even if the links are correct.

--track
--no-track

When creating a new branch, if<commit-ish> is a branch,mark it as "upstream" from the new branch. This is thedefault if<commit-ish> is a remote-tracking branch. See--track ingit-branch[1] for details.

--lock

Keep the worktree locked after creation. This is theequivalent ofgitworktreelock aftergitworktreeadd,but without a race condition.

-n
--dry-run

Withprune, do not remove anything; just report what it wouldremove.

--orphan

Withadd, make the new worktree and index empty, associatingthe worktree with a new unborn branch named<new-branch>.

--porcelain

Withlist, output in an easy-to-parse format for scripts.This format will remain stable across Git versions and regardless of userconfiguration. It is recommended to combine this with-z.See below for details.

-z

Terminate each line with aNUL rather than a newline when--porcelain is specified withlist. This makes it possibleto parse the output when a worktree path contains a newlinecharacter.

-q
--quiet

Withadd, suppress feedback messages.

-v
--verbose

Withprune, report all removals.

Withlist, output additional information about worktrees (see below).

--expire<time>

Withprune, only expire unused worktrees older than<time>.

Withlist, annotate missing worktrees as prunable if they are older than<time>.

--reason<string>

Withlock or withadd--lock, an explanation why the worktreeis locked.

<worktree>

Worktrees can be identified by path, either relative or absolute.

If the last path components in the worktree’s path is unique amongworktrees, it can be used to identify a worktree. For example if you onlyhave two worktrees, at/abc/def/ghi and/abc/def/ggg, thenghi ordef/ghi is enough to point to the former worktree.

REFS

When using multiple worktrees, some refs are shared between all worktrees,but others are specific to an individual worktree. One example isHEAD,which is different for each worktree. This section is about the sharingrules and how to access refs of one worktree from another.

In general, all pseudo refs are per-worktree and all refs starting withrefs/ are shared. Pseudo refs are ones likeHEAD which are directlyunder$GIT_DIR instead of inside$GIT_DIR/refs. There are exceptions,however: refs insiderefs/bisect,refs/worktree andrefs/rewritten arenot shared.

Refs that are per-worktree can still be accessed from another worktree viatwo special paths,main-worktree andworktrees. The former givesaccess to per-worktree refs of the main worktree, while the latter to alllinked worktrees.

For example,main-worktree/HEAD ormain-worktree/refs/bisect/goodresolve to the same value as the main worktree’sHEAD andrefs/bisect/good respectively. Similarly,worktrees/foo/HEAD orworktrees/bar/refs/bisect/bad are the same as$GIT_COMMON_DIR/worktrees/foo/HEAD and$GIT_COMMON_DIR/worktrees/bar/refs/bisect/bad.

To access refs, it’s best not to look inside$GIT_DIR directly. Insteaduse commands such asgit-rev-parse[1] orgit-update-ref[1]which will handle refs correctly.

CONFIGURATION FILE

By default, the repositoryconfig file is shared across all worktrees.If the config variablescore.bare orcore.worktree are present in thecommon config file andextensions.worktreeConfig is disabled, then theywill be applied to the main worktree only.

In order to have worktree-specific configuration, you can turn on theworktreeConfig extension, e.g.:

$ git config extensions.worktreeConfig true

In this mode, specific configuration stays in the path pointed bygitrev-parse--git-pathconfig.worktree. You can add or updateconfiguration in this file withgitconfig--worktree. Older Gitversions will refuse to access repositories with this extension.

Note that in this file, the exception forcore.bare andcore.worktreeis gone. If they exist in$GIT_DIR/config, you must movethem to theconfig.worktree of the main worktree. You may also take thisopportunity to review and move other configuration that you do not want toshare to all worktrees:

  • core.worktree should never be shared.

  • core.bare should not be shared if the value iscore.bare=true.

  • core.sparseCheckout should not be shared, unless you are sure youalways use sparse checkout for all worktrees.

See the documentation ofextensions.worktreeConfig ingit-config[1] for more details.

DETAILS

Each linked worktree has a private sub-directory in the repository’s$GIT_DIR/worktrees directory. The private sub-directory’s name is usuallythe base name of the linked worktree’s path, possibly appended with anumber to make it unique. For example, when$GIT_DIR=/path/main/.git thecommandgitworktreeadd/path/other/test-nextnext creates the linkedworktree in/path/other/test-next and also creates a$GIT_DIR/worktrees/test-next directory (or$GIT_DIR/worktrees/test-next1iftest-next is already taken).

Within a linked worktree,$GIT_DIR is set to point to this privatedirectory (e.g./path/main/.git/worktrees/test-next in the example) and$GIT_COMMON_DIR is set to point back to the main worktree’s$GIT_DIR(e.g./path/main/.git). These settings are made in a.git file located atthe top directory of the linked worktree.

Path resolution viagitrev-parse--git-path uses either$GIT_DIR or$GIT_COMMON_DIR depending on the path. For example, in thelinked worktreegitrev-parse--git-pathHEAD returns/path/main/.git/worktrees/test-next/HEAD (not/path/other/test-next/.git/HEAD or/path/main/.git/HEAD) whilegitrev-parse--git-pathrefs/heads/master uses$GIT_COMMON_DIR and returns/path/main/.git/refs/heads/master,since refs are shared across all worktrees, exceptrefs/bisect,refs/worktree andrefs/rewritten.

Seegitrepository-layout[5] for more information. The rule ofthumb is do not make any assumption about whether a path belongs to$GIT_DIR or$GIT_COMMON_DIR when you need to directly access somethinginside$GIT_DIR. Usegitrev-parse--git-path to get the final path.

If you manually move a linked worktree, you need to update thegitdir filein the entry’s directory. For example, if a linked worktree is movedto/newpath/test-next and its.git file points to/path/main/.git/worktrees/test-next, then update/path/main/.git/worktrees/test-next/gitdir to reference/newpath/test-nextinstead. Better yet, rungitworktreerepair to reestablish the connectionautomatically.

To prevent a$GIT_DIR/worktrees entry from being pruned (whichcan be useful in some situations, such as when theentry’s worktree is stored on a portable device), use thegitworktreelock command, which adds a file namedlocked to the entry’s directory. The file contains the reason inplain text. For example, if a linked worktree’s.git file pointsto/path/main/.git/worktrees/test-next then a file named/path/main/.git/worktrees/test-next/locked will prevent thetest-next entry from being pruned. Seegitrepository-layout[5] for details.

Whenextensions.worktreeConfig is enabled, the config file.git/worktrees/<id>/config.worktree is read after.git/config is.

LIST OUTPUT FORMAT

Theworktreelist command has two output formats. The default format shows thedetails on a single line with columns. For example:

$ git worktree list/path/to/bare-source            (bare)/path/to/linked-worktree        abcd1234 [master]/path/to/other-linked-worktree  1234abc  (detached HEAD)

The command also shows annotations for each worktree, according to its state.These annotations are:

  • locked, if the worktree is locked.

  • prunable, if the worktree can be pruned viagitworktreeprune.

$ git worktree list/path/to/linked-worktree    abcd1234 [master]/path/to/locked-worktree    acbd5678 (brancha) locked/path/to/prunable-worktree  5678abc  (detached HEAD) prunable

For these annotations, a reason might also be available and this can beseen using the verbose mode. The annotation is then moved to the next lineindented followed by the additional information.

$ git worktree list --verbose/path/to/linked-worktree              abcd1234 [master]/path/to/locked-worktree-no-reason    abcd5678 (detached HEAD) locked/path/to/locked-worktree-with-reason  1234abcd (brancha)locked: worktree path is mounted on a portable device/path/to/prunable-worktree            5678abc1 (detached HEAD)prunable: gitdir file points to non-existent location

Note that the annotation is moved to the next line if the additionalinformation is available, otherwise it stays on the same line as theworktree itself.

Porcelain Format

The porcelain format has a line per attribute. If-z is given then the linesare terminated with NUL rather than a newline. Attributes are listed with alabel and value separated by a single space. Boolean attributes (likebareanddetached) are listed as a label only, and are present onlyif the value is true. Some attributes (likelocked) can be listed as a labelonly or with a value depending upon whether a reason is available. The firstattribute of a worktree is alwaysworktree, an empty line indicates theend of the record. For example:

$ git worktree list --porcelainworktree /path/to/bare-sourcebareworktree /path/to/linked-worktreeHEAD abcd1234abcd1234abcd1234abcd1234abcd1234branch refs/heads/masterworktree /path/to/other-linked-worktreeHEAD 1234abc1234abc1234abc1234abc1234abc1234adetachedworktree /path/to/linked-worktree-locked-no-reasonHEAD 5678abc5678abc5678abc5678abc5678abc5678cbranch refs/heads/locked-no-reasonlockedworktree /path/to/linked-worktree-locked-with-reasonHEAD 3456def3456def3456def3456def3456def3456bbranch refs/heads/locked-with-reasonlocked reason why is lockedworktree /path/to/linked-worktree-prunableHEAD 1233def1234def1234def1234def1234def1234bdetachedprunable gitdir file points to non-existent location

Unless-z is used any "unusual" characters in the lock reason such as newlinesare escaped and the entire reason is quoted as explained for theconfiguration variablecore.quotePath (seegit-config[1]).For Example:

$ git worktree list --porcelain...locked "reason\nwhy is locked"...

EXAMPLES

You are in the middle of a refactoring session and your boss comes in anddemands that you fix something immediately. You might typically usegit-stash[1] to store your changes away temporarily, however, yourworking tree is in such a state of disarray (with new, moved, and removedfiles, and other bits and pieces strewn around) that you don’t want to riskdisturbing any of it. Instead, you create a temporary linked worktree tomake the emergency fix, remove it when done, and then resume your earlierrefactoring session.

$ git worktree add -b emergency-fix ../temp master$ pushd ../temp# ... hack hack hack ...$ git commit -a -m 'emergency fix for boss'$ popd$ git worktree remove ../temp

CONFIGURATION

Everything below this line in this section is selectively includedfrom thegit-config[1] documentation. The content is the sameas what’s found there:

worktree.guessRemote

If no branch is specified and neither-b nor-B nor--detach is used, thengitworktreeadd defaults tocreating a new branch from HEAD. Ifworktree.guessRemote isset to true,worktreeadd tries to find a remote-trackingbranch whose name uniquely matches the new branch name. Ifsuch a branch exists, it is checked out and set as "upstream"for the new branch. If no such match can be found, it fallsback to creating a new branch from the currentHEAD.

worktree.useRelativePaths

Link worktrees using relative paths (when "true") or absolutepaths (when "false"). This is particularly useful for setupswhere the repository and worktrees may be moved betweendifferent locations or environments. Defaults to "false".

Note that settingworktree.useRelativePaths to "true" implies enabling theextensions.relativeWorktrees config (seegit-config[1]),thus making it incompatible with older versions of Git.

BUGS

Multiple checkout in general is still experimental, and the supportfor submodules is incomplete. It is NOT recommended to make multiplecheckouts of a superproject.

GIT

Part of thegit[1] suite


[8]ページ先頭

©2009-2025 Movatter.jp