Skip to main content

My Go-To Git Commands to Fix Mistakes

· 3 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

Added Bonus

In some cases, a branch name may be reused, causing conflicts between the local and remote branches. One such example is when Renovate bot creates and reuses branches for the same x.y.z version. After merging and deleting the remote branch of one version, the local branch may still exist. Thus, when you try to check out the branch of a new PR for another version update locally, you may have branch divergence issues, To resolve this, you can force your local branch to reset to the remote branch.

git reset --hard @{u}
  • u stands for upstream, which refers to the remote branch.