Git Undo Scenarios

Mansoor Aldosari
2 min readMay 8, 2022
Photo by Ian Romie Ona on Unsplash

It’s good to have a mental model of git. There are three trees within git:

  • Working tree: local files.
  • Index: staging area; the middle ground; it takes a file from the working tree and prepares it for a commit.
  • HEAD: points to the last commit.

The Initialization Step:

First, let’s initialize a git repository:

$git init

Create a file. The status will show the working directory in red:

$touch foo
$git status

Add the file to the staging area. The status will show the index in green:

$git add foo
$git status

Now, we commit the file:

$git commit -m “add foo”
$git status

If we modify the file, we should perform the same steps of adding and committing:

$echo "hello" >> foo
$git status
$git add foo
$git status
$git commit -m “change foo”
$git status

The Undo Step:

Before staging, after staging, and post staging:

1. Before staging: this will discard changes made in the working tree.

$git restore foo

2. After staging: this will remove the file from the staging area.

$git restore --staged foo

3. Post staging: this will revert to the previous commit of the file.

$git revert foo

This step will revert to an old commit by adding a new commit:

$git log --oneline
* 5c13080 (HEAD -> master) revert "change foo"
* b1c91f2 change foo
* 41d3aa1 add foo

GLHF, fellow developers!

--

--