Oh Shit Git
Oh Shit, Git!?!
Magic Time Machine
Oh shit, I did something terribly wrong, please tell me git has a magic time machine!?
git reflog
# you will see a list of everything you've done in git, across all branches
# each one has an index like HEAD@{index}
# find the one before you broke everything
git reset HEAD@{index}
# magic time machine
git reset --hard HEAD@{6}
You can use this to recover accidentally deleted work, undo bad merges, or go back to a time when things actually worked.
reflog is extremely powerful and very commonly used for recovery.
Add Small Change After Committed
Oh shit, I committed and immediately realized I need to make one small change!
# make your change
git add . # or add individual files
git commit --amend --no-edit
Your last commit now includes the new change.
⚠️ Warning: Never amend commits that have already been pushed to a public/shared branch.
Change Last Commit Message
Oh shit, I need to change the message on my last commit!
git commit --amend -m "Updated commit message"
Follow the prompts to update the commit message.
Commit to a New Branch Instead of Master
Oh shit, I accidentally committed something to master that should have been on a new branch!
# create a new branch from current state
git branch some-new-branch-name
# remove last commit from master
git reset HEAD~ --hard
# switch to new branch
git checkout some-new-branch-name
Your commit now lives safely in the new branch.
⚠️ This does not work if the commit was already pushed to a public branch.
Rectify Committing to the Correct Branch
Oh shit, I accidentally committed to the wrong branch!
Method 1: Stash
git reset HEAD~ --soft
git stash
git checkout name-of-the-correct-branch
git stash pop
git add .
git commit -m "your message here"
Method 2: Cherry-pick
git checkout name-of-the-correct-branch
git cherry-pick master
git checkout master
git reset HEAD~ --hard
Differences Not Showing
Oh shit, I ran diff but nothing happened!?
If files were already staged, use:
git diff --staged
Undo n-th Commit
Oh shit, I need to undo a commit from several commits ago!
git log
# find the commit hash
git revert <commit-hash>
Git creates a new commit that reverses the selected commit.
Undo Changes to a File
Oh shit, I need to undo my changes to a file!
git log
# find a commit before the change
git checkout <commit-hash> -- path/to/file
git commit -m "Reverted file to previous version"
Delete and Restart
Fuck this noise, I give up.
cd ..
sudo rm -r fucking-git-repo-dir
git clone https://some.github.url/fucking-git-repo-dir.git
cd fucking-git-repo-dir
Hard Reset to Remote (Destructive)
If your branch is completely broken and you want to reset to the remote state:
git fetch origin
git checkout master
git reset --hard origin/master
git clean -d --force
Repeat checkout / reset / clean for any other broken branches.