Git Undo Scenarios

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!




Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to Git cherry-pick only changes to certain files

CS373 Fall 2020: Week 4

How to Set Up a Private Blockchain Network with XDC Network Codebase.

Why is server-side WebAssembly exciting, and why now?

Banking Digital Transformation — A Quality Engineering perspective

Mockups mock immediate programming

Nutbox (NUT)

Morgan Stanley Internship Experience

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Mansoor Aldosari

Mansoor Aldosari

More from Medium

What are file test operators in Bash Scripting

What are file test operators in Bash Scripting

How to Copy a folder across multiple user accounts on a Linux Ubuntu 20.0 Virtual Machine on azure.

This is the structure of directories on the hard drive.

How to install Linux bash shell on Windows 10

Linux Basic Commands: Part 2