I was working on a branch and needed to get back on master for a quick fix so I committed my work in progress.
Now I am back in my branch and I would like to get back to the state where I haven't committed but all my changes are applied and ready to be committed (i.e. cancel the previous commit but my changes are not lost and they are shown in git status
).
Amending the previous commit is not good enough for me as I want to see the changed files and lines (it makes it easier to work on my change).
I know git stash would have been a better solution but it's too late. I also tend to mix up (or loose) my stashed commits as they are not linked to a branch.
The easiest way to undo the last Git commit is to execute the “git reset” command with the “–soft” option that will preserve changes done to your files. You have to specify the commit to undo which is “HEAD~1” in this case. The last commit will be removed from your Git history.
The revert command You can find the name of the commit you want to revert using git log . The first commit that's described there is the last commit created. Then you can copy from there the alphanumerical name and use that in the revert command.
To undo the last commit from a remote git repository, you can use the git reset command. command. This will undo the last commit locally. command to force push the local commit which was reverted to the remote git repository.
There are basically two ways to solve this:
Do a reset (on the master
branch, or whatever branch the false commit is):
git reset --soft HEAD~1
The HEAD~1
is a relative address as explained here.
Keep working and perform an amendment:
git commit --amend
In that case you pretend nothing happened, work further on your branch and call the command when you were planning to do a real commit. You kind of overwrite the last commit with all changes and (optionally) a new message.
And pro forma: it is indeed - as you mention yourself - better to perform a git stash
, only saying for people that see this answer by accident and think the above is common practice (it is not).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With