The best answers to the question “Branch from a previous commit using Git” in the category Dev.
If I have n commits, how can I branch from the n-3 commit?
I can see the hash of every commit.
To do this on github.com:
- Go to your project.
- Click on the “Commits”.
- Click on the <> (“Browse the repository at this point in the history”) on the commit you want to branch from.
- Click on the “tree: xxxxxx” up in the upper left. Just below the language statistics bar, you’ll get the option to “Find or Create Branch” (just type in a new branch name there)
You can create the branch via a hash:
git branch branchname <sha1-of-commit>
Or by using a symbolic reference:
git branch branchname HEAD~3
To checkout the branch when creating it, use
git checkout -b branchname <sha1-of-commit or HEAD~3>
If you are not sure which commit you want to branch from in advance you can check commits out and examine their code (see source, compile, test) by
git checkout <sha1-of-commit>
once you find the commit you want to branch from you can do that from within the commit (i.e. without going back to the master first) just by creating a branch in the usual way:
git checkout -b <branch_name>
The magic can be done by git reset.
Create a new branch and switch to it (so all of your latest commits are stored here)
git checkout -b your_new_branch
Switch back to your previous working branch (assume it’s master)
git checkout master
Remove the latest x commits, keep master clean
git reset --hard HEAD~x # in your case, x = 3
From this moment on, all the latest x commits are only in the new branch, not in your previous working branch (master) any more.