TL;DR: Reset to the last commit state. My favorite commands (just about it easy to type)
1git checkout . 2 3git reset --hard HEAD
Sometimes, in developer life, there are some cases that you might want to revert back all changes made to your feature branch.
For example:
- You are coding on a feature/bug fixing, but then realizing that you went for the wrong way and wanted to start it again in the brand new code.
- You do some experiments on the source code, then wanted to return it back once the jobs are completed.
- You wanted to pull/checkout code from remote, but Git does not allow you to do it, since there are still unstaged changes remaining in the code base. However, you do not need it anymore, just return it back to the previous pristine state.
Now it’s time for the tips!
No rollback - Unstaged only
ERASE changes in current directory (including files and folders)
1# All files and sub-folders
2git checkout .
3
4# Specific file only
5git checkout -- <file_path>
- No branch specified, so current branch picked
.
indicates all path--
to indicated file path
Or git restore
from Git 2.23
1# Form Git 2.23 (August 2019)
2git restore .
3
4# Specific file only
5git restore -- <file_path>
No rollback - Both unstaged and staged only
A more powerful way to enforce reset to last commit (remember, no rollback):
1git reset --hard HEAD
2
3# or shorter
4
5git reset --hard
Git clean - Added files only
We can simply use git clean
1git clean -df
-d
as directory-f
as force-n
(optional) as dry-run (safety option)-x
(optional) as ignore to ignore rules from.gitignore
Can be reverted back
There’s way to add changes to stash then popping it out in case of needed
1# Adding to stash
2
3git stash -u
4
5git stash -u -m "<message to remind>"
Once the changes is already in stash, you can re-apply to the current code by the following commands
1# Revert changes
2
3git stash pop # Lost the stash
4
5git stash apply @{<stash_index>} # Still keep the stash
References
P/s: to be continuously added…
Thanks for reading!
- Previous
Git Alias - The shorthand power | Git in-use - Next
Git Tips - Reset a branch to remote status | Git in-use