626

Possible Duplicate / a more recent/less clear question
Branch from a previous commit using Git

I have a Git branch called jzbranch and have an old commit id: a9c146a09505837ec03b.

How do I create a new branch, justin, from the information listed above?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
JZ.
  • 19,005
  • 31
  • 110
  • 185
  • 54
    This isn't a duplicate--the other question deals with retrieving from a certain NUMBER of commits back while this question uses a COMMIT ID. – Anton Feb 22 '13 at 15:56
  • create new branch with current commit, then checkout back to original branch and then revert to old commit – Muhammad Umer Mar 03 '20 at 19:48

1 Answers1

1093
git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME
Trevor Boyd Smith
  • 15,512
  • 24
  • 110
  • 159
bdonlan
  • 205,037
  • 27
  • 244
  • 316
  • 118
    It is worth noting that if you had checked out a commit using `git checkout ` (and therefore you're on a **detached** `HEAD`), you can create a branch at that commit by just using `git branch ` or `git checkout -b ` (no `SHA1` argument required for the same commit). – ADTC Aug 26 '14 at 09:31
  • 2
    Just thought I would add that this technique also works when you accidentally drop a stash. – WORMSS May 22 '17 at 07:24
  • 4
    if you're creating a new branch for others to use, but don't have any commits yet, you can push with: `git push --set-upstream origin justin` – Kip Jan 09 '20 at 16:03
  • what does "check it out" mean?? – mesqueeb Jan 31 '20 at 01:01
  • 2
    @mesqueeb I suppose it means switching to the branch. The first command create a new branch and switches directly to it. The second one create a new branch without directly switching to it, so you will be still on older branch. – slawkens Jun 03 '20 at 18:28