DEV Community

z z
z z

Posted on

5 Git Commands I Wish I Knew 5 Years Ago

Most Git tutorials show you add, commit, push. But the commands that actually save you are the ones nobody teaches. Here are 5 I use weekly.


1. git reflog — Your Undo History

Ever deleted a branch or lost commits after a bad rebase? git reflog shows EVERYTHING you've done in Git for the last 90 days.

git reflog
# Find the hash of your lost commit, then:
git checkout <hash>           # View it
git branch recovered <hash>   # Save it
Enter fullscreen mode Exit fullscreen mode

This has saved me more times than I can count.


2. git bisect — Find the Bug Automatically

Instead of checking commits one by one to find when a bug was introduced, let Git do a binary search:

git bisect start
git bisect bad HEAD          # Current version has the bug
git bisect good v1.0         # v1.0 was working fine
# Git checks out the middle commit. Test it:
git bisect good              # or: git bisect bad
# Repeat until Git tells you the exact commit that broke things
Enter fullscreen mode Exit fullscreen mode

From hours of manual checking to 5 iterations.


3. git stash — Switch Context in 1 Second

You're working on a feature, and suddenly need to fix a critical bug on main. Don't commit half-done work:

git stash                    # Save all changes and go back to clean state
git checkout main            # Switch to main, fix the bug
git checkout feature-branch  # Come back
git stash pop                # Restore your in-progress work
Enter fullscreen mode Exit fullscreen mode

4. git reset --soft HEAD~1 — Undo Without Losing Work

Made a commit too early? Want to split it or change the message? This undoes the last commit but keeps all your changes staged:

git reset --soft HEAD~1
# Your files are exactly as they were. Just re-commit when ready.
Enter fullscreen mode Exit fullscreen mode

(If you want to delete the changes too, use --hard instead — but careful.)


5. git push --force-with-lease — The Safe Force Push

Never use git push --force. It silently overwrites other people's work. Use this instead:

git push --force-with-lease
Enter fullscreen mode Exit fullscreen mode

It only pushes if nobody else has pushed to the same branch since you last fetched. If someone did, it rejects — saving you from accidentally deleting their commits.


Want More?

These 5 commands cover 80% of Git emergencies. For the other 20% (recovering from bad rebases, splitting commits, fixing detached HEAD, and 47 more recipes), I wrote a guide:

👉 Git Rescue Guide — $4.99 on Gumroad

Instant PDF download. Read it once, keep it forever.


What Git command saved you the most time? Drop it in the comments!

Top comments (0)