1

so I have a commit hash from earlier in a project. How can I create a new worktree and have it's branch start from this specific commit?

2 Answers2

3

Create the branch before worktree:

git branch newbranch $SHA1
git worktree add /path/to/wt newbranch
phd
  • 82,685
  • 13
  • 120
  • 165
2

Use the command described in the git worktree documentation:

git worktree add [--detach] [-b <new-branch>] <path> [<commit-ish>]

which in this case might be, e.g.:

$ cd gitrepo
$ git worktree add -b workbranch ../gitrepo.workbranch d16c37964
Preparing ../gitrepo.workbranch (identifier gitrepo.workbranch)
HEAD is now at d16c37964 Merge branch 'jk/attributes-path-doc'

after which:

$ cd ../gitrepo.workbranch
$ git status
On branch workbranch
nothing to commit, working tree clean
$ git rev-parse HEAD
d16c37964c284fa599251caafb51128c0df925a9
torek
  • 448,244
  • 59
  • 642
  • 775
  • thanks! I'm trying this now and will respond with results. One thing that confused me in the doc is the use of [ and ] around certain cli flags. What purpose do they serve? – Michael Palumbo Apr 12 '18 at 17:45
  • 1
    Square brackets indicate that something is optional. See https://stackoverflow.com/questions/9725675/is-there-a-standard-format-for-command-line-shell-help-text – torek Apr 12 '18 at 18:25
  • thanks @torek !! so seems to be working for me now! one thing I will note, however, is that running both --detach and -b in the command results in an error stating that -b -B and --detach are mutually exclusive, so I have for now removed --detach from the command. may I ask: why do you think --detach should be in the command? – Michael Palumbo Apr 12 '18 at 20:51
  • The text on a yellow background (StackOverflow's marker for quoting) is where I literally copied from the documentation, and merely shows all (well, ok, most of) the options. The text on a grey background is what I wrote, which does not use `--detach`. You would use `--detach` to force the worktree into "detached HEAD" mode when using an existing branch name. Beware of `-B` (uppercase B), which can forcibly reset an existing branch name to point to a specific commit. – torek Apr 12 '18 at 21:03