Skip to main content

My Go-To Git Commands to Fix Mistakes

· 2 min read

These are the scenarios that I often find myself searching for Git commands to save me from my mistakes.

Common Scenarios

  1. Forgot to create a new branch for feature development or bug fixes and worked on the develop/main branch.
  2. Forgot to pull the latest changes from the remote branch before making local adjustments.

Scenario 1: If I Have Not Added the Files

# Stash the changes to keep them aside
git stash
# Pull the latest changes from the remote branch
git pull
# Alternatively, create and switch to a new branch
git checkout -b <branch-name>
# Reapply the stashed changes
git stash pop
# Continue with development, then add, commit, and push as usual

Scenario 2: If I Have Added/Staged the Files

# Unstage the files
git reset
# Stash the changes to keep them aside
git stash
# Pull the latest changes from the remote branch
git pull
# Alternatively, create and switch to a new branch
git checkout -b <branch-name>
# Reapply the stashed changes
git stash pop
# Continue with development, then add, commit, and push as usual

Scenario 3: If I Have Committed the Files (Once) and Not Yet Pushed

# Undo the latest local commit but keep the changes
git reset --soft HEAD~1
# Alternatively, undo the latest local commit and discard the changes
git reset --hard HEAD~1
# Pull the latest changes from the remote branch
git pull
# Continue with development, then add, commit, and push as usual