Home > Software engineering >  Assign HEAD to previous commit without losing the HEAD
Assign HEAD to previous commit without losing the HEAD

Time:06-08

I have a commit(A) in my local repository which I do not intend to push yet. Right now, the HEAD is at A. Let's say I want to create another commit(B) NOT on top of commit(A), but on top of the previous commit than commit(A).

How do I assign my local HEAD to the previous commit without losing the latest commit(A)?

I DO NOT want to undo/remove commit(A), I want to save it for later to rebase to the latest commit in my branch. After creating the commit B, I want to put commit(A) on top of commit(B).

Kind of like :-

C1 -> C2 -> A(HEAD)

to finally

C1 -> C2 -> B -> A(HEAD) (eventually)

How can I do this?

Edit :- I have a restriction to do this without using another branch.

CodePudding user response:

With rebase

You could create a new commit now, then rebase -i to re-order them.

 (create B)
 git rebase -i head˜2
 (in the resulting pick list, re-order A and B)
 (Use `dd` and `P` to delete and paste lines)
 !wq // Exit vim 

With a temporary branch

 git checkout -b temp
 git reset --hard head˜1
 (create B)
 git cherry-pick A
 git checkout - // Checkout whatever your previous branch was
 git reset --hard temp

CodePudding user response:

From your branch,

# Save your branch with its commit A on a new branch
git branch backup_A

# Restore your branch one commit back
git reset --hard HEAD~

Your commit A will wait for you on the backup_A branch while you work on B.

When you're done with your commit B and want A on top, just cherry-pick it back :

git cherry-pick backup_A
  •  Tags:  
  • git
  • Related