I checked out a previous commit, using git checkout , I made changes, and committed them. However, when I do git status, it says HEAD detached from . How can I make commit that I've checked out the commit I want to keep going forward?
Let's look at the situation step by step. Initially you were at the head of a branch, let's say it was master
:
--A--B--C
^ master
HEAD
I checked out a previous commit, using git checkout
git checkout HEAD~
Now you're here:
--A--B--C
^ ^ master
HEAD
This situation is called "detached HEAD" because HEAD
(the current pointer) is not at the head of any branch.
I made changes, and committed them.
Now you're here:
--D < HEAD
/
--A--B--C
^ master
What do you want to do now? Do you want to drop the commit C
at the head of master
and move master
to where your HEAD
is (to D
)? Or do you want to move the commit D
to master
(preserving C
)?
The first task can be solved with the following commands:
git branch tmp-master # create a new branch
tmp-master
v
--D < HEAD
/
--A--B--C
^ master
git checkout master
tmp-master
v
--D
/
--A--B--C < HEAD
^ master
git reset --hard tmp-master # move the branch
git branch -D tmp-master # remove the temporary branch
master
v HEAD
--D
/
--A--B--C
Or, to streamline the new master
branch:
--A--B--D
\
C
The commit C
becomes a dangling commit and sooner or later will be removed by garbage collector.
But if you want to do the second task (preserve both C
and D
) the steps are a bit different:
git branch tmp-master # create a new branch
tmp-master
v
--D < HEAD
/
--A--B--C
^ master
git checkout master
tmp-master
v
--D
/
--A--B--C < HEAD
^ master
git cherry-pick tmp-master
git branch -D tmp-master # remove the temporary branch
--A--B--C--D' < HEAD
^ master
Just reset to that commit.
git reset --hard <commit_id>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With