Undo
Whoops, we messed up, what now?
Undo changes after staging
Change the text again to “hello devine”, stage these changes via the add command, but don’t commit it yet:
You get a hint on how to unstage these changes: via git restore —staged:
The file is still changed, but the changes are not staged anymore.
You can now definitively undo this, by using —just like in the previous topic— git restore:
Undo commits
Let’s say you’ve committed some changes, but for some reason you want to undo them.
You can do 2 things: either create a new commit that undoes the changes from the previous commit (git revert HEAD
), or completely clear the commit from history (git reset --hard _reference-to-commit_
).
Your terminal will now display a vim or nano editor, into which you can type a commit message. Edit the default message if you want, and type in vim :quit
when you’re done. For nano, use Ctrl + X, followed by Yes.
The file will now contain the contents from before the last commit.
You can also set a different editor for the merge message edits. Instead of vim, nano is a more user-friendly alternative:
By the way, you can view a repository’s commit history with the git log
command:
You can see that the “wrong” commit is still in the git history, and the changes were undone via a new commit. Also note that each commit has a unique SHA1 hash ID. You can use these IDs to specify commits on certain commands.
A more drastic way to undo commits is with the git reset
command. With git reset you are going to reset your working tree to a particular commit and delete all commits after that commit from the repository.
We want to go back to the state of our commit “welcome + new world file”. Through git log, we find out that the SHA1 ID is 9720321677e0798b540b287398edeaadcb630b17
. Specify the SHA1 ID of the commit to where you want to reset after the command. You don’t have to specify the entire ID: the first 4 characters are often sufficient (at least if they are unique):
Now when you run git log again, you will see that the commits after 9720 are gone:
You will only use such a git reset
command to undo local commits. Once you’re collaborating with others, and commits have already been distributed to other users, you use the git revert
command to create a new commit that undoes a previous commit.