Git Command Recipes & Emergency Solutions
Instant terminal solutions for the most searched Git emergencies. How to undo commits, discard changes, resolve conflicts, stash files, recover lost commits with reflog, and rename branches safely.
How to Undo the Last Commit in Git
Undo your most recent Git commit while keeping all your edited files staged or unstaged in your working directory.
git reset --soft HEAD~1How to Discard All Local Changes in Git
Discard all unstaged and uncommitted file modifications and restore your working tree to the latest commit.
git restore .How to Rename a Local and Remote Git Branch
Rename your current local branch and update the upstream remote tracking branch on GitHub or GitLab.
git branch -m <old-name> <new-name>How to Delete a Remote Branch in Git
Delete a branch from remote origin (GitHub, GitLab, Bitbucket) after a pull request has been merged.
git push origin --delete <branch-name>How to Change the Most Recent Git Commit Message
Amend the commit message of your latest commit before or after pushing.
git commit --amend -m "new message"How to Unstage Files from Git (Undo git add)
Remove files from the Git staging area (index) without losing any of your local changes.
git restore --staged <file>How to Stash Untracked and Modified Files in Git
Temporarily shelve both modified and newly created untracked files to switch branches with a clean working copy.
git stash -uHow to Force Git Pull to Overwrite Local Files
Completely overwrite your local repository with the exact state of the remote branch.
git fetch origin && git reset --hard origin/mainHow to Cherry-Pick a Commit to Another Branch
Apply a specific commit from one branch onto your current branch without merging the entire branch.
git cherry-pick <commit-hash>How to Stop Tracking a File in Git Without Deleting It
Remove a committed file (such as .env or local config) from Git tracking while preserving the file on your local disk.
git rm --cached <file-path>How to Squash Multiple Commits into One with Git Rebase
Combine multiple messy "wip" or "fix typo" commits into a single clean, atomic commit.
git rebase -i HEAD~NHow to Resolve Git Merge Conflicts Accepting Ours or Theirs
Quickly resolve merge conflicts across files by accepting all changes from your branch (--ours) or the incoming branch (--theirs).
git checkout --ours <file> OR git checkout --theirs <file>How to View Git Commit History as a Beautiful One-Line Graph
Format git log into an easy-to-read ASCII branch graph with short hashes, relative dates, author, and branch labels.
git log --oneline --graph --decorate --allHow to Revert a Merged Pull Request in Git
Safely revert an accidentally merged Pull Request or merge commit using git revert with parent specification.
git revert -m 1 <merge-commit-hash>How to Recover Deleted Commits or Branches with Git Reflog
Find and restore commits or branches that were accidentally lost after a hard reset, bad rebase, or branch deletion.