How to Revert Local Changes to Previous State in Git

Ashok Chapagai Feb 02, 2024
  1. Revert Unstaged Local Changes in Git
  2. Revert Staged Local Changes in Git
How to Revert Local Changes to Previous State in Git

Let’s assume Mario was assigned a task and was about to complete it, but alas, the client changed their requirement and asked Mario to stop working on the previously assigned task, then what would be the perfect solution to this dilemma?

In this article, you will learn how to revet local changes to the previous state in Git.

Revert Unstaged Local Changes in Git

If you have not used the command git add, which generally pushes the file to stage, you can easily navigate to the previous state following the steps below.

  • Confirm the status of the files with git status.
    $ git status
    On branch dev
    Your branch is up to date with 'origin/dev'.
    
    Changes not staged for commit:
      (use "git add <file>..." to update what will be committed)
      (use "git restore <file>..." to discard changes in working directory)
    	modified:   frontend/src/index.tsx
    	modified:   frontend/src/common/components/index.tsx
    	modified:   frontend/src/common/components/index.css
    
  • With the status being known, you can use any options below according to your preference.
    • Overwrite local changes
    git checkout -- <file>
    
    • Save local changes to be able to use later in the project,
    git stash
    
    • Discard all the changes made in the files
    git reset --hard
    

Revert Staged Local Changes in Git

If you have added the files using the git add command, we can revert it to the previous state by following the below steps.

  • Use git status to confirm the availability of added file.
  • Now that you have seen the files staged, you can choose the file you want to revert and use the following command according to the situation.
    1. Keep changes to the file but without leaving it on staged.
    git restore --staged <file_name_with.path>
    
    1. Unstage all the files keeping changes,
    git reset
    
    1. Discard all the changes and save them for later use.
    git stash
    

    Note: Use git stash pop to undo the effect of git stash and use git stash list to list available stashes.

    1. Discard everything
    git reset --hard
    
Ashok Chapagai avatar Ashok Chapagai avatar

Ashok is an avid learner and senior software engineer with a keen interest in cyber security. He loves articulating his experience with words to wider audience.

LinkedIn GitHub

Related Article - Git Revert