How do I discard unstaged changes in Git?

How do I discard unstaged changes in Git?

So, to restore all unstaged files in the current working directory, use:

git restore .

To restore a specific file, use:

git restore path/to/file/to/revert

Together with git switch, these commands replace the overloaded git checkout and remove the need for argument disambiguation.

If a file has both staged and unstaged changes, only the unstaged changes (those shown in git diff) are reverted. Changes shown in git diff --staged remain intact.

Before Git 2.23

To restore all unstaged files in the current working directory:

git checkout -- .

To restore a specific file:

git checkout -- path/to/file/to/revert

The -- is used to remove ambiguity, known as argument disambiguation.

Another quicker way is:

To stash all changes, including unstaged and untracked files, while keeping the index (staged changes) intact, you can use:

git stash save --keep-index --include-untracked

You can omit --include-untracked if you only want to stash unstaged changes.

After stashing, you can drop that stash using git stash drop if you no longer need it.

The complete solution to remove all untracked files and clear all unstaged changes is:

  1. Use git clean -df to remove all untracked files. Note that this command may delete ignored files residing in folders.

  2. Use git checkout -- . to clear all unstaged changes. This command will revert all changes made to tracked files in the current directory.

Together, these commands effectively remove all untracked files and clear all unstaged changes. However, be cautious with git clean -df as it may delete ignored files mentioned directly in .gitignore.