Getting Git

A comprehensive video course from git init to Git Master.

Master: git reset


In this video we'll learn some more advanced usages of git reset.

We saw in the init video how to use git reset to undo commands like git add and git rm.

However, we can also use reset to undo git commit as well as undo all of our changes.

Let's take a look at undoing git commit.

To demonstrate this let's remove File 1 and commit that change.

I'll run:

git rm file-1.txt

and then:

git commit –m 'Removing file-1.txt'

When I run git status I see the repository is in a clean state.

If I run ls I see the file has also been deleted.

By using git reset, we undo the commit and place the changes back in the index.

Said another way, it resets the Git repository to its state right before the commit.

Let's demonstrate this by running:

git reset SHA^

(passing it the SHA followed by a caret)

We'll learn about the caret in Part 2. For now, what's important is that git reset needs a reference to the SHA of the commit before the one we want to undo. So, we can suffix the SHA of the commit we want to undo with a caret to provide git reset the correct reference.

If I run git status I see the change to delete file again.

Now it's important to note git reset did not completely undo the commit.

In this case the file is still deleted from the file system.

If I wanted to completely undo changes I can use the ––hard option.

Let's remake the commit so we can run git reset again with the --hard option.

So we'll the same Git commands again.

But this time, we'll run git reset with the --hard option and pass in the new commit SHA.

If we run git status we see the current state is clean.

And if I run ls we see the file exists.

You can use the --hard option at any time to reset the current state back to its previously clean state.

So if I just made some changes and decided I wanted to discard them, I could simply run:

git reset --hard

However, be mindful git reset --hard is a destructive command.

While we'll learn how to potentially undo such destructive commands in Everyday Git, there are no guarantees.

So anytime you add the --hard option, its a good idea to reconfirm your intentions.