Use case
You have uncommited changes (you can always check by using git status
), which you want to discard.
Context
Now there are several options to discard these depending on your exact situation.
The headlines will differentiate the cases whether the files are staged or unstaged.
Staged and unstaged changes
Revert all changes to modified files (tracked and untracked)
git reset --hard
If you might want to use the changes later on
git stash
will add the changes to the stash, reverting the local repository to HEAD.
From there on you have several options what you can do with the changes, most widely used are probably
-
git stash apply
to apply your stashed changes -
git stash drop
to delete your stashed changes -
git stash pop
to apply your staged changes and delete them at the same time
Revert back all uncommitted tracked changes made in your local repository
git checkout [path to file]
- Might be as simple as
git checkout .
Revert to the state of a specific commit:
git checkout [commit hash] [file path]
, where the commit hash can be found by using git log
Revert to the state of a specific branch:
You can use this command to checkout files from another branch if you might want to revert to this state by using git checkout <other-branch-name> -- [path]
Staged changes
Unstage all staged files
-
git reset HEAD [file path]
-
[path to file]
is optional
-
-
git restore --staged [file path]...
- When you have merged your branch you can use
--merge
flag to recreate the conflicted state in the unmerged paths.
- When you have merged your branch you can use
Now you can use any command to discard unstaged changes.
Unstaged Changes
Remove all untracked files and directories
git clean -fd
Info
If you want to remove ignored files as well, use
git clean -fdx
.
Revert the changes only within a specific path
git checkout -- [path]
-
Path could be
.
for the current working directory or any actual path (e.g.app/views/some_model/index.html.erb
) were you want to revert the changes -
You can list the files that will be reverted by checking
git checkout --
Special path options:
-
git checkout -- *
the star checks all files in current directory and recursively in subdirectories. -
git checkout -- '**/*.rb'
checks for the given pattern -
git checkout -- :/
to checkout all files across the whole repository
Restore a specific file / folder
git restore [file path]
-
.
for complete directory
Info
- By using the
--patch
(or just-p
) flag you can restore change selectively in the command line.- You could specify a different source as well by using
-s
flag
For more details check the card on Git restore.
Also see