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?
Asked
Active
Viewed 2.5k times
3 Answers
55
do not use --hard
use --soft
instead.
Thus if you want to remove your latest commit you'd do:
git reset --soft HEAD^

Alexander Oh
- 24,223
- 14
- 73
- 76
-
@cherrun, also consider reading [Reset Demystified](http://git-scm.com/2011/07/11/reset.html). – kostix Jul 15 '12 at 12:28
-
1+1 for a short and accurate answer. To sum up, use: `git reset --soft HEAD~1` – VarunPandey Nov 22 '16 at 00:38
-
1[reset demystified](https://git-scm.com/book/en/v2/Git-Tools-Reset-Demystified) has moved – jrubins Aug 17 '18 at 19:39
5
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.

Seth Robertson
- 30,608
- 7
- 64
- 57
-
1great answer! I think this is about only throwing some changes away that were made in the last commit and keeping the other half. In that case you would just throw away the commit and adding the changes again, that you intend to keep. in this case `git add --interactive` might be useful too! – Alexander Oh Jul 14 '12 at 10:21
2
for my case, i prefer using --mixed
instead, after i found this simple explanation
git reset --mixed HEAD^

el hafizh hidayat
- 66
- 4