Predictive Hacks

How to Undo Changes in Git

Undo Working Directory Changes

We will show you how to “undo” changes in Git. Assume that accidentally we removed a file.

Let’s remove the “myfile.txt

git rm myfile.txt
git status

So if we want to restore the file, we can run:

git restore myfile.txt

How to Unstage a File

Let’s say that you accidentally staged a file by running the command “git add myfilename” and you want to unstage the file. Then you can simply run:

git reset HEAD myfilename

How to Retrieve Older Versions

Let’s say that we want to retrieve an older version of a file. Let’s see how we can do it. We have to go to the log history by running the “git log” command and choose the SHA code of the older version (the first characters are enough). Then you run the command “git checkout <SHA>”. For example

git checkout 0dd6680

And you will get the following message:

Note: switching to '0dd6680'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by switching back to a branch.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -c with the switch command. Example:

  git switch -c <new-branch-name>

Or undo this operation with:

  git switch -

Turn off this advice by setting config variable advice.detachedHead to false

HEAD is now at 0dd6680 another change

If we run the command:

cat myfile.txt

You will see that we are in an older version. The checkout output command above explains the situation. These changes can be retained if we create a new branch.

You will see that you are in a “detached HEAD” state, and you may freak out because you cannot go back to your latest version in the master branch. Let’s see how we can go back.

git checkout main

And we get the message:

Previous HEAD position was 0dd6680 another change
Switched to branch 'main'
Your branch is up to date with 'origin/main'.

How to Revert a Commit

We can revert a past commit by running

git revert <SHA>

How to Remove Untracked Files

Let’s say that you have added some files that should not be tracked, and you want to get rid of them, then you can run:

git clean -n

Which is a “dryrun” and shows you which files will be removed and once you are sure, you can run:

git clean -f

You may be interested in a Git and GitHub Cheatsheet

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s