Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Permanently continue work from previous commit

Tags:

git

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?

like image 224
TheRealFakeNews Avatar asked Sep 01 '25 10:09

TheRealFakeNews


2 Answers

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
like image 154
phd Avatar answered Sep 04 '25 06:09

phd


Just reset to that commit.

git reset --hard <commit_id>
like image 26
hspandher Avatar answered Sep 04 '25 07:09

hspandher