How to Discard All Changes in Git: Simple Commands
To discard all changes in Git, use
git restore . to undo changes in tracked files and git clean -fd to remove untracked files and directories. Alternatively, git reset --hard resets all changes including staged files to the last commit.Syntax
Here are the main commands to discard changes in Git:
git restore .: Discards changes in all tracked files in the current directory.git clean -fd: Removes all untracked files and directories.git reset --hard: Resets the working directory and staging area to the last commit, discarding all changes.
bash
git restore . git clean -fd git reset --hard
Example
This example shows how to discard all changes including untracked files:
bash
$ git status On branch main 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: file1.txt Untracked files: (use "git add <file>..." to include in what will be committed) newfile.txt $ git restore . $ git clean -fd $ git status On branch main nothing to commit, working tree clean
Output
On branch main
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: file1.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
newfile.txt
On branch main
nothing to commit, working tree clean
Common Pitfalls
Common mistakes when discarding changes:
- Using
git reset --hardwithout saving important changes causes permanent loss. - Forgetting to remove untracked files with
git clean -fdleaves unwanted files behind. - Running these commands in the wrong directory can discard changes unintentionally.
bash
$ git reset --hard # This will discard all changes including staged ones # Wrong: forgetting to clean untracked files $ git restore . # Untracked files remain # Right: clean untracked files too $ git clean -fd
Quick Reference
| Command | Purpose |
|---|---|
| git restore . | Discard changes in all tracked files |
| git clean -fd | Remove untracked files and directories |
| git reset --hard | Reset working directory and staging area to last commit |
Key Takeaways
Use git restore . to discard changes in tracked files safely.
Run git clean -fd to remove all untracked files and directories.
git reset --hard resets everything but will permanently lose changes.
Always check git status before discarding to avoid losing work.
Run these commands in the correct directory to avoid unintended data loss.