Undoing and redoing commits is part of everyday life, so it’s important to understand the commands that can help us along the way. In this pro tip I will teach you how to do two things:
- Undo the last commit so you can keep the changes on staging;
- Reuse the content of the undone commit to make a new commit.
With these two commands in your repertoire of Git commands, you will be way happier. 😉
Creating the scenario
I talked about the command
git reset in this other pro tip. In a nutshell, it is a command that allows you to return to a previous state. The most basic use of this command is to use it to undo one or more of the most recent commits. With that, let’s assume you’re in the following situation (interestingly I went through this last Friday):
- You committed to the wrong branch;
- You haven’t pushed this new commit to the remote yet;
- You want to undo this commit and redo it to the correct branch.
As an example, I have here a history of a project in which there are two commits: the initial commit on the
main branch (
d815be) and the second commit (
arquivo-1.txt that should be on another branch, see:
Now it’s time to undo our wrong commit.
Undoing the last commit softly
Given this scenario, the first step is to use the command
git reset. Maybe you don’t know that there is a flag that while undoing a commit with
git reset, it allows you to keep the commit changes on staging and the commit message stored in a special variable that I’ll show you in a bit. That flag is
So we can create our command like this:
git reset HEAD^ --soft
--soft indicates that you want to undo the commit subtly, in other words, keeping the changes. When running this command, you will not get any message, but the changes are on staging, which you can check with the command
git status, and the result is as follows:
Now let’s redo the commit in the right place and reuse the message.
Reusing the commit message
Now that you’ve undone the commit and you have the changes on staging, you can create the new branch and switch to it. I mentioned this previous command in this other pro tip just in case you want to check it out:
git switch -c add-arquivos-novos
With that, the long-awaited moment arrives! You probably already know that to make commits, you need to use the command
git commit. As our
soft-like, the commit message was stored in the variable
ORIG_HEAD, so to reuse it you should use the flag
-C followed by the variable, like this:
git commit -C ORIG_HEAD
-C literally means “reuse message”, and this is the result:
Finally, if you want to edit the message, you should use the flag
-c in place of the current flag. This will give you the opportunity to adjust the previous message before finishing the commit.
GitFichas | GitStudyCards
Hope these commands help you to reuse the work done.