How do I create a new Git branch from an old commit?

343,034
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
Share:
343,034
JZ.
Author by

JZ.

go engineer @easypost.

Updated on July 16, 2022

Comments

  • JZ.
    JZ. almost 2 years

    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?

  • ADTC
    ADTC almost 10 years
    It is worth noting that if you had checked out a commit using git checkout <SHA1> (and therefore you're on a detached HEAD), you can create a branch at that commit by just using git branch <branchname> or git checkout -b <branchname> (no SHA1 argument required for the same commit).
  • WORMSS
    WORMSS about 7 years
    Just thought I would add that this technique also works when you accidentally drop a stash.
  • Kip
    Kip over 4 years
    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
  • mesqueeb
    mesqueeb over 4 years
    what does "check it out" mean??
  • slawkens
    slawkens about 4 years
    @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.