I mostly use below git commands in my daily development so this post will be updated frequently.
Staging
git add file1.txt file2.txt
git add *.java
or
git add docs/*.md
or
git add *test*.js
git add src/ docs/
git add .
or
git add -A
Unstaging
git reset file1.txt file2.txt
or
git restore --staged file1.txt file2.txt
git reset src/ docs/
or
git restore --staged src/ docs/
git reset
or
git restore --staged .
Discarding
git restore file1.txt file2.txt
git restore src/ docs/
git restore .
Unstage and Discard
git reset file1.txt file2.txt
git restore file1.txt file2.txt
or
git restore --staged file1.txt file2.txt
git restore file1.txt file2.txt
git reset src/ docs/
git restore src/ docs/
or
git restore --staged src/ docs/
git restore src/ docs/
git reset
git restore .
or
git restore --staged .
git restore .
Completely Discard all local commits, staged and unstaged changes
to discard all changes (both staged and unstaged) and reset the working directory to the last commit.
git reset --hard
git reset --hard origin/main
Undo Local Last Commit but Keep Changes
HEAD~1
refers to the commit just before the currentHEAD
.- The
--soft
option keeps your changes in the staging area.
git reset --soft HEAD~1
Undo Local Last Commit and Unstage Changes
git reset --mixed HEAD~1
Undo Local Last Commit and Discarding Changes
This command undoes the last commit and discards all the changes made in that commit. The changes are not kept in the staging area or working directory.
git reset --hard HEAD~1
Summary
# Undo and keep changes staged:
$ git reset --soft HEAD~1
# Undo and move changes to working directory:
$ git reset --mixed HEAD~1
# Undo and discard changes:
$ git reset --hard HEAD~1
# Undo by creating a new commit that reverses the changes:
$ git revert HEAD
Restore commit
Assume that you undo last commit as staged, then you need to restore it. You can undo last commit by running git reset --soft HEAD~1
then run git reflog
to view logs, then you can run git reset --hard HEAD@{1}
to reset previous commit in reflog.
HEAD~1
: Resets to the commit immediately before the current one, based on commit history.HEAD@{1}
: Resets to the previous state ofHEAD
as recorded in the reflog, which could be the commit before a reset, merge, or other operation that movedHEAD
.
git reset --soft HEAD~1
git reset --hard HEAD@{1}
Even you undo last two commits, it will represented one line in reflog, so we could restore to last commit.
git reset --soft HEAD~2
git reset --hard HEAD@{1}
git reset --soft HEAD~3
git reset --hard origin/main
List commits
$ git log
or
$ git log --oneline
or
$ git log --name-only
or
$ git log --name-only --oneline
or
$ git log --name-status
or
$ git log --name-status --oneline
or
$ git log --stat
or
$ git log --stat --oneline
or
$ git log --graph --oneline --decorate --all