hitesh
hitesh

Reputation: 177

Assign HEAD to previous commit without losing the HEAD

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). So it should look like :-

Before : C -> A(HEAD)

After : C -> B -> A(HEAD)

How can I do this?

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

Upvotes: 2

Views: 96

Answers (2)

Romain Valeri
Romain Valeri

Reputation: 21938

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

Upvotes: 3

RJFalconer
RJFalconer

Reputation: 11662

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

Upvotes: 4

Related Questions