git_reset_and_checkout
git reset & checkout
Undo changes and navigate commits.
π git reset
Soft Reset (Keep Changes Staged)
git reset --soft HEAD~1
Undoes last commit but keeps changes staged. Ready to re-commit.
Mixed Reset (Keep Changes Unstaged)
git reset HEAD~1
Undoes last commit, unstages changes, but keeps them in working directory.
Hard Reset (Discard Everything)
git reset --hard HEAD~1
β οΈ Undoes last commit AND discards all changes. Cannot be recovered easily.
Reset to Specific Commit
git reset --hard abc1234
Resets to specific commit. All subsequent commits are removed.
Reset to Remote Branch
git reset --hard origin/main
Makes local branch identical to remote.
Unstage File (Keep Changes)
git reset HEAD filename.txt
Removes file from staging area but keeps changes in working directory.
Unstage All Files
git reset HEAD
Unstages all files while keeping changes.
π Reset Modes Comparison
| Mode | HEAD | Index | Working Dir |
|---|---|---|---|
--soft |
β Moves | Unchanged | Unchanged |
--mixed |
β Moves | β Reset | Unchanged |
--hard |
β Moves | β Reset | β Reset |
π Reset Flow
graph TD
A[git reset --soft] --> B[Move HEAD only]
C[git reset --mixed] --> D[Move HEAD + Reset staging]
E[git reset --hard] --> F[Move HEAD + Reset staging + Reset working dir]
β©οΈ git checkout (Legacy for Files)
Discard Changes in File
git checkout -- filename.txt
Discards uncommitted changes in file. Restores from last commit.
Checkout File from Commit
git checkout abc1234 -- filename.txt
Restores file to state at specific commit.
Checkout File from Branch
git checkout main -- filename.txt
Gets file from
mainbranch into current branch.
β©οΈ git restore (Modern)
Discard Working Directory Changes
git restore filename.txt
Modern alternative to
checkout --. Discards uncommitted changes.
Discard All Changes
git restore .
Discards all uncommitted changes in current directory.
Unstage File
git restore --staged filename.txt
Modern way to unstage a file.
Restore from Commit
git restore --source=abc1234 filename.txt
Restores file from specific commit.
Restore from HEAD~2
git restore --source=HEAD~2 filename.txt
Restores file from 2 commits ago.
π git switch (Modern for Branches)
Switch Branch
git switch branch-name
Modern alternative to
checkoutfor switching branches.
Create and Switch
git switch -c new-branch
Creates new branch and switches to it.
Switch to Previous Branch
git switch -
Switches to the previous branch you were on.
π¨ Recovery After Hard Reset
View Lost Commits
git reflog
Shows history of where HEAD was. Find lost commit hash.
Recover Lost Commit
git reset --hard abc1234
Reset to the commit hash found in reflog.
π‘ Tips
git reset --hard discards work permanently. Use git stash first if unsure.
Use git restore for files and git switch for branches.
π Related
#git #reset #checkout #restore #undo #advanced