[git] How to create the branch from specific commit in different branch

I have made several commits in the master branch and then merged them to dev branch.

I want to create a branch from a specific commit in dev branch, which was first committed in master branch.

I used the commands:

git checkout dev
git branch  <branch name> <commit id>

However, this creates the branch from master branch, not the dev branch I expected. The commit id is same in master branch and dev branch. So, how can I distinguish same commit id in different branch?

PS: I made an example in github here https://github.com/RolandXu/test_for_branch

I used the commands:

git checkout dev
git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8

What I expect is that the test branch contains aa.txt bb.txt cc.txt. However, the test branch only contains aa.txt and cc.txt. It most likely created the branch from the master branch.

This question is related to git git-branch

The answer is


You have the arguments in the wrong order:

git branch <branch-name> <commit>

and for that, it doesn't matter what branch is checked out; it'll do what you say. (If you omit the commit argument, it defaults to creating a branch at the same place as the current one.)

If you want to check out the new branch as you create it:

git checkout -b <branch> <commit>

with the same behavior if you omit the commit argument.


You have to do:

git branch <branch_name> <commit>

(you were interchanging the branch name and commit)

Or you can do:

git checkout -b <branch_name> <commit>

If in place of you use branch name, you get a branch out of tip of the branch.


You can do this locally as everyone mentioned using

git checkout -b <branch-name> <sha1-of-commit>

Alternatively, you can do this in github itself, follow the steps:

1- In the repository, click on the Commits.

2- on the commit you want to branch from, click on <> to browse the repository at this point in the history.

commits history

3- Click on the tree: xxxxxx in the upper left. Just type in a new branch name there click Create branch xxx as shown below.

create new branch

Now you can fetch the changes from that branch locally and continue from there.


Try

git checkout <commit hash>
git checkout -b new_branch

The commit should only exist once in your tree, not in two separate branches.

This allows you to check out that specific commit and name it what you will.