Three Habits for a Clean Git History

gitignore · git stash · git rebase

Shreya Anekar

The part tutorials skip

Beyond fork · clone · branch · commit · push

Most people learn how to make commits. Almost no one learns how to keep a repository and its history clean.

Three small habits do most of the work:

gitignore

Prevent the mess. Stop junk from ever entering the repo.

git stash

Avoid the mess. Set work aside without a junk commit.

git rebase

Fix the mess. Rewrite messy commits into clean ones.

Prevent it, avoid it, or fix it, and your history stays readable.

1 · .gitignore

Prevent the mess

A plain text file that tells Git which files to never track. You commit code, not the things around it:

  • Data — *.csv, *.parquet, raw datasets
  • Secrets — .env files, API keys
  • Build output — _site/, __pycache__/
  • Artifacts — trained models, large binaries
# .gitignore  →  lives at the root of your repo
*.csv                 # data stays out of version control
.env                  # never commit credentials
__pycache__/          # Python noise
/_site/  /.quarto/    # Quarto build output

A leaked key or a 2 GB file buried in history is painful to undo. Prevention always beats cleanup.

2 · git stash

Avoid the mess

You’re mid-edit when something urgent pulls you to another branch. Your changes aren’t ready to commit. What now?

✗ The messy way

git commit -m "WIP dont look"

A throwaway commit that clutters history forever.

✓ The clean way

git stash      # set aside
git checkout main
git stash pop  # bring back

Your work is parked safely, then restored untouched.

zsh — ~/portfolio
~/portfolio (main) $ git stash # shelve current work
Saved working directory and index state WIP on main
~/portfolio (main) $ git checkout feature
~/portfolio (feature) $ git stash pop # bring it right back
✓ changes restored — exactly where you left off

3 · git rebase -i

Fix the mess

Real working history is honest, and honestly ugly:

* a1b2c3d  fix typo again
* d4e5f6g  oops forgot import
* h7i8j9k  WIP
* p3q4r5s  add customer dedup logic

No reviewer wants to read “oops” and “WIP”. Interactive rebase lets you rewrite these before anyone sees them:

git rebase -i HEAD~4     # edit the last 4 commits

In the editor, change pick to squash to fold commits together:

pick   p3q4r5s  add customer dedup logic
squash h7i8j9k  WIP
squash d4e5f6g  oops forgot import
squash a1b2c3d  fix typo again

The payoff

Fix the mess

Four noisy commits become one you’d be proud to ship:

Before

* fix typo again
* oops forgot import
* WIP
* add dedup logic

After

* Add customer dedup
  logic with null
  handling + tests

Warning

Golden rule: rebase only commits you haven’t shared yet. Rewrite local history freely, but never rewrite main.

A clean history is a gift to your reviewer, and to future you.

Thank you