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

Bonus

If you have Git hooks set up, you will likely encounter situations where you need to bypass them. A genuine use case is when you want to create a branch for work in progress or intentionally broken logic for testing purposes. To bypass the hooks, use the --no-verify flag with the git commit command.

git commit -m "Commit message" --no-verify