Michael Lee Kha Michael Lee Kha - 6 months ago 35
Git Question

How to merge deteched commits to master

I tried to create new branch from a certain commit of master. I don't remember the command I used but I think this one (but not sure)

git branch branchname <sha1-of-commit>

I got a new branch with a bunch of commits. But I found that master branch lost all commits that found in new branch. Changes related with lost commits were also lost in master branch.

It looks like I detached a bunch of commits from master to new branch. Actually I never wanted master branch to lost its commits. How can I restore those detached commit to master?

Please see the illustration of my problem below:

Some random commits were detached to new branch

Answer Source

So, Commit 4, 7, 8, 10 and 13 are on the new branch and you want them to be in master instead.

You can't move into a detached HEAD state, with that command above, you will you will have to do

git checkout <sha-1 of commit>


git checkout branchname

So its most likely you ran another commit that has messed things, use

git reflog

to try and find out where things went wrong.

However, if you ran the right command, and you can't remember. To merge that branch back into master.

1/ Do a checkout to commit 13, I am assuming that's the final commit you made on the detached HEAD state.

git checkout <sha-1 of commit 13>

2/ Give that branch a name, this means give this branch a name, that makes checkout to it later easier.If you do run

git branch -a 

You'll get something like this

(detached from <sha-1 of commit 13)
*Other branches

To rename the branch do;

git checkout -b <branch-name>

Then list the branches again

*Other branches

3/ Merging is easy now, simply checkout to your master branch and merge

git checkout master
git merge <branch-name>


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download