Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "reopen" the last git commit?

Tags:

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.

like image 773
Matthieu Napoli Avatar asked Apr 09 '15 00:04

Matthieu Napoli


People also ask

How do I reopen a last commit?

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.

Can we revert the last commit in git?

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.

How do I revert my last remote commit?

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.


1 Answers

There are basically two ways to solve this:

  1. 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.

  2. 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).

like image 166
Willem Van Onsem Avatar answered Oct 03 '22 14:10

Willem Van Onsem