Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset without losing already committed files

Tags:

When I accidentally committed a file to the wrong branch, I normally use git reset --hard HEAD~1. However, using this method I generally lose all the files committed. Is there a way to reset a commit, without losing the edited files?

like image 906
cherrun Avatar asked Jul 14 '12 08:07

cherrun


People also ask

How do you go back to previous commit without losing changes?

To jump back to a previous commit, first find the commit's hash using git log . This places you at commit 789abcd . You can now make new commits on top of this old commit without affecting the branch your head is on. Any changes can be made into a proper branch using either branch or checkout -b .

Does git reset remove commit history?

To remove the last commit from git, you can simply run git reset --hard HEAD^ If you are removing multiple commits from the top, you can run git reset --hard HEAD~2 to remove the last two commits. You can increase the number to remove even more commits.

Does git reset keep changes?

git reset --soft , which will keep your files, and stage all changes back automatically.


2 Answers

do not use --hard use --soft instead.

Thus if you want to remove your latest commit you'd do:

git reset --soft HEAD^

like image 147
Alexander Oh Avatar answered Jan 27 '23 01:01

Alexander Oh


While Alex is very correct, I might be tempted to try a different sequence:

If I wanted the commit on a yet-to-be-born branch:

git branch newbranch git reset --hard HEAD^ 

If I wanted the commit on an existing branch:

git checkout otherbranch git cherry-pick firstbranch git checkout firstbranch git reset --hard HEAD^ 

The full example of Alex's answer

git reset --soft HEAD^ git checkout otherbranch git commit -am "Message" 

Note the last example will fail poorly if the attempt to "float" the change to the other branch fails due to conflicts. You will then need to stash/checkout/apply to get into conflict resolution.

like image 23
Seth Robertson Avatar answered Jan 27 '23 01:01

Seth Robertson