[git] How do I revert all local changes in Git managed project to previous state?

I have a project in which I ran git init. After several commits, I did git status which told me everything was up to date and there were no local changes.

Then I made several consecutive changes and realized I wanted to throw everything away and get back to my original state. Will this command do it for me?

git reset --hard HEAD

This question is related to git revert git-checkout

The answer is


Look into git-reflog. It will list all the states it remembers (default is 30 days), and you can simply checkout the one you want. For example:

$ git init > /dev/null
$ touch a
$ git add .
$ git commit -m"Add file a" > /dev/null
$ echo 'foo' >> a
$ git commit -a -m"Append foo to a" > /dev/null
$ for i in b c d e; do echo $i >>a; git commit -a -m"Append $i to a" ;done > /dev/null
$ git reset --hard HEAD^^ > /dev/null
$ cat a
foo
b
c
$ git reflog
145c322 HEAD@{0}: HEAD^^: updating HEAD
ae7c2b3 HEAD@{1}: commit: Append e to a
fdf2c5e HEAD@{2}: commit: Append d to a
145c322 HEAD@{3}: commit: Append c to a
363e22a HEAD@{4}: commit: Append b to a
fa26c43 HEAD@{5}: commit: Append foo to a
0a392a5 HEAD@{6}: commit (initial): Add file a
$ git reset --hard HEAD@{2}
HEAD is now at fdf2c5e Append d to a
$ cat a
foo
b
c
d

Note: You may also want to run

git clean -fd

as

git reset --hard

will not remove untracked files, where as git-clean will remove any files from the tracked root directory that are not under git tracking. WARNING - BE CAREFUL WITH THIS! It is helpful to run a dry-run with git-clean first, to see what it will delete.

This is also especially useful when you get the error message

~"performing this command will cause an un-tracked file to be overwritten"

Which can occur when doing several things, one being updating a working copy when you and your friend have both added a new file of the same name, but he's committed it into source control first, and you don't care about deleting your untracked copy.

In this situation, doing a dry run will also help show you a list of files that would be overwritten.


Try this for revert all changes uncommited in local branch

$ git reset --hard HEAD

But if you see a error like this:

fatal: Unable to create '/directory/for/your/project/.git/index.lock': File exists.

You can navigate to '.git' folder then delete index.lock file:

$ cd /directory/for/your/project/.git/
$ rm index.lock

Finaly, run again the command:

$ git reset --hard HEAD

This question is more about broader repository reset / revert, but in case if you're interested in reverting individual change - I've added similar answer in here:

https://stackoverflow.com/a/60890371/2338477

Answers to questions:

  • How to revert individual change with or without change preserving in git history

  • How to return back to old version to restart from same state


I searched for a similar issue,

Wanted to throw away local commits:

  1. cloned the repository (git clone)
  2. switched to dev branch (git checkout dev)
  3. did few commits (git commit -m "commit 1")
  4. but decided to throw away these local commits to go back to remote (origin/dev)

So did the below:

git reset --hard origin/dev

Check:

git status  

        On branch dev  
        Your branch is up-to-date with 'origin/dev'.  
        nothing to commit, working tree clean  

now local commits are lost, back to the initial cloned state, point 1 above.


I met a similar problem. The solution is to use git log to look up which version of the local commit is different from the remote. (E.g. the version is 3c74a11530697214cbcc4b7b98bf7a65952a34ec).

Then use git reset --hard 3c74a11530697214cbcc4b7b98bf7a65952a34ec to revert the change.


If you want to revert all changes AND be up-to-date with the current remote master (for example you find that the master HEAD has moved forward since you branched off it and your push is being 'rejected') you can use

git fetch  # will fetch the latest changes on the remote
git reset --hard origin/master # will set your local branch to match the representation of the remote just pulled down.

Re-clone

GIT=$(git rev-parse --show-toplevel)
cd $GIT/..
rm -rf $GIT
git clone ...
  • ? Deletes local, non-pushed commits
  • ? Reverts changes you made to tracked files
  • ? Restores tracked files you deleted
  • ? Deletes files/dirs listed in .gitignore (like build files)
  • ? Deletes files/dirs that are not tracked and not in .gitignore
  • You won't forget this approach
  • Wastes bandwidth

Following are other commands I forget daily.

Clean and reset

git clean --force -d -x
git reset --hard
  • ? Deletes local, non-pushed commits
  • ? Reverts changes you made to tracked files
  • ? Restores tracked files you deleted
  • ? Deletes files/dirs listed in .gitignore (like build files)
  • ? Deletes files/dirs that are not tracked and not in .gitignore

Clean

git clean --force -d -x
  • ? Deletes local, non-pushed commits
  • ? Reverts changes you made to tracked files
  • ? Restores tracked files you deleted
  • ? Deletes files/dirs listed in .gitignore (like build files)
  • ? Deletes files/dirs that are not tracked and not in .gitignore

Reset

git reset --hard
  • ? Deletes local, non-pushed commits
  • ? Reverts changes you made to tracked files
  • ? Restores tracked files you deleted
  • ? Deletes files/dirs listed in .gitignore (like build files)
  • ? Deletes files/dirs that are not tracked and not in .gitignore

Notes

Test case for confirming all the above (use bash or sh):

mkdir project
cd project
git init
echo '*.built' > .gitignore
echo 'CODE' > a.sourceCode
mkdir b
echo 'CODE' > b/b.sourceCode
cp -r b c
git add .
git commit -m 'Initial checkin'
echo 'NEW FEATURE' >> a.sourceCode
cp a.sourceCode a.built
rm -rf c
echo 'CODE' > 'd.sourceCode'

See also

  • git revert to make new commits that undo prior commits
  • git checkout to go back in time to prior commits (may require running above commands first)
  • git stash same as git reset above, but you can undo it

After reading a bunch of answers and trying them, I've found various edge cases that mean sometimes they don't fully clean the working copy.

Here's my current bash script for doing it, which works all the time.

#!/bin/sh
git reset --hard
git clean -f -d
git checkout HEAD

Run from working copy root directory.


DANGER AHEAD: (please read the comments. Executing the command proposed in my answer might delete more than you want)

to completely remove all files including directories I had to run

git clean -f -d

Adding another option here.

I'm referring to the title: Revert local changes.
It can also apply to changes that weren't staged for commit.

In this case you can use:

git restore <file>

To go back to previous state.


simply execute -

git stash

it will remove all your local changes. and you can also use it later by executing -

git stash apply 

You may not necessarily want/need to stash your work/files in your working directory but instead simply get rid of them completely. The command git clean will do this for you.

Some common use cases for doing this would be to remove cruft that has been generated by merges or external tools or remove other files so that you can run a clean build.

Keep in mind you will want to be very cautious of this command, since its designed to remove files from your local working directory that are NOT TRACKED. if you suddently change your mind after executing this command, there is no going back to see the content of the files that were removed. An alternative which is safer is to execute

git stash --all

which will remove everything but save it all in a stash. This stash can then later be used.

However, if you truly DO want to remove all the files and clean your working directory, you should execute

git clean -f -d

This will remove any files and also any sub-directories that don't have any items as a result of the command. A smart thing to do before executing the git clean -f -d command is to run

git clean -f -d -n

which will show you a preview of what WILL be removed after executing git clean -f -d

So here is a summary of your options from most aggressive to least aggressive


Option 1: Remove all files locally(Most aggressive)

git clean -f -d

Option 2: Preview the above impact(Preview most aggressive)

git clean -f -d -n

Option 3: Stash all files (Least aggressive)

`git stash --all` 

Examples related to git

Does the target directory for a git clone have to match the repo name? Git fatal: protocol 'https' is not supported Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools) git clone: Authentication failed for <URL> destination path already exists and is not an empty directory SSL_connect: SSL_ERROR_SYSCALL in connection to github.com:443 GitLab remote: HTTP Basic: Access denied and fatal Authentication How can I switch to another branch in git? VS 2017 Git Local Commit DB.lock error on every commit How to remove an unpushed outgoing commit in Visual Studio?

Examples related to revert

How do you revert to a specific tag in Git? How do I revert an SVN commit? How do I "un-revert" a reverted Git commit? git revert back to certain commit Reverting to a previous revision using TortoiseSVN Remove specific commit Reverting single file in SVN to a particular revision How can I revert a single file to a previous version? Mercurial — revert back to old version and continue from there git status shows modifications, git checkout -- <file> doesn't remove them

Examples related to git-checkout

How can I switch to another branch in git? Git checkout - switching back to HEAD What is git tag, How to create tags & How to checkout git remote tag(s) How can I move HEAD back to a previous location? (Detached head) & Undo commits error: pathspec 'test-branch' did not match any file(s) known to git git checkout all the files How can I check out a GitHub pull request with git? "Cannot update paths and switch to branch at the same time" error: Your local changes to the following files would be overwritten by checkout Git command to checkout any branch and overwrite local changes