my-notes

git_reset_and_checkout

2 min read

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 main branch 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 checkout for 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

Hard Reset is Dangerous

git reset --hard discards work permanently. Use git stash first if unsure.

Modern Commands

Use git restore for files and git switch for branches.



#git #reset #checkout #restore #undo #advanced

Built with mdgarden