Git Best Practices
Git best practices are habits that keep a repository easy to work with for everyone: a history that explains itself, branches that merge without drama, and no secrets or junk inside. None of them is enforced by Git. Each one is a lesson that teams learned, often the hard way. This lesson collects them into one checklist, with the reason for each, and links to the lesson that explains the commands.
A tidy workshop is not tidy by accident. Tools go back on the wall after use, offcuts go in the bin, and dangerous materials are locked away. Nobody remembers a single big clean-up. They remember small habits, repeated every day.
The Checklist
| # | Practice | Why |
|---|---|---|
| 1 | Commit small, focused changes | Each commit can be understood, reviewed, reverted and cherry-picked on its own |
| 2 | Write clear commit messages | The history explains itself months later ("Writing Good Commit Messages") |
| 3 | Use a branch for every task | main stays stable, and work can be reviewed before merging |
| 4 | Keep branches short-lived | The longer a branch lives, the harder its merge |
| 5 | Pull (or fetch) before you start, and before you push | You build on the newest work and avoid rejected pushes |
| 6 | Check before you commit | git status and git diff --staged show exactly what goes in |
| 7 | Never commit secrets | Anything pushed must be considered public ("Removing Files from History") |
| 8 | Never commit generated files | Build output, dependencies and IDE files belong in .gitignore |
| 9 | Review every change before it reaches main | A second pair of eyes catches bugs and spreads knowledge |
| 10 | Don't rewrite shared history | Rebase and amend only your own unpushed commits, and never force-push main |
| 11 | Force-push only with a lease | --force-with-lease --force-if-includes protects teammates' work |
| 12 | Tag every release | Anyone can find and rebuild exactly what users have |
| 13 | Protect important branches | The platform enforces reviews and checks, not just good intentions |
| 14 | Configure Git once, properly | Identity, line endings and useful defaults avoid surprises |
The rest of this lesson shows a few of them in practice.
Practice 1 and 6: Small Commits, Checked Before Committing
A commit should do one thing. If git status shows several unrelated changes, stage them separately, with git add <file> or git add -p for parts of a file ("Git Add: Staging Changes"):
mkdir fee-tracker
cd fee-tracker
git init --quiet
echo "Fee Tracker" > README.md
echo 'Term 1 fee: $12,000' > fees.txt
git add .
git commit --quiet -m "Start the project"
echo 'Late fee: $250' >> fees.txt
echo "Run the app to see the fees." >> README.md
git status -s
git add fees.txt
git diff --staged --stat
git commit --quiet -m "Add the late fee"
git add README.md
git commit --quiet -m "Explain how to run the app"
git log --oneline M README.md
M fees.txt
fees.txt | 1 +
1 file changed, 1 insertion(+)
76f7bcf (HEAD -> main) Explain how to run the app
48cb415 Add the late fee
b3a928f Start the projectExplanation: the two changes, a new fee and a README sentence, became two commits. git diff --staged --stat confirmed what was about to be committed. Either commit can now be reverted without touching the other.
Practice 7 and 8: Keep Secrets and Junk Out
The easiest way to keep files out of history is a .gitignore written on the first day. Here is a quick audit of a repository where that was forgotten:
mkdir target
echo "compiled" > target/App.class
echo "DB_PASSWORD=chalk42" > .env
echo "started" > app.log
git add .
git commit --quiet -m "Add everything"
git ls-files.env
README.md
app.log
fees.txt
target/App.classBuild output, a password file and a log file are now tracked. To clean up: write a .gitignore, stop tracking the files (they stay on disk), and commit both. Then change the password, because it is in the history now:
printf "target/\n.env\n*.log\n" > .gitignore
git rm --quiet -r --cached target .env app.log
git add .gitignore
git commit --quiet -m "Stop tracking build output, logs and local settings"
git ls-files
git status -s --ignored.gitignore
README.md
fees.txt
!! .env
!! app.log
!! target/The files are untracked and ignored. A ready-made .gitignore for Java (from GitHub's templates, or the one in "Git .gitignore") at the start would have prevented all of it.
Practice 14: Configure Git Once
A handful of settings make everyday Git safer and smoother. Set them once with --global:
git config --global init.defaultBranch main
git config --global pull.rebase true
git config --global push.autoSetupRemote true
git config --global fetch.prune true
git config --global merge.conflictStyle zdiff3
git config --global rerere.enabled true
git config --global --list | grep -v "^user\."init.defaultbranch=main
pull.rebase=true
push.autosetupremote=true
fetch.prune=true
merge.conflictstyle=zdiff3
rerere.enabled=truegit config --list prints setting names in lower case. They aren't case-sensitive, so pull.rebase and pull.Rebase are the same setting.
| Setting | Effect |
|---|---|
init.defaultBranch main | New repositories start with main |
pull.rebase true | Pulls rebase your local commits instead of creating merge commits |
push.autoSetupRemote true | The first push of a new branch sets its upstream automatically |
fetch.prune true | Fetches remove copies of branches deleted on the server |
merge.conflictStyle zdiff3 | Conflict markers also show the original lines |
rerere.enabled true | Git remembers how you resolved a conflict and reuses it next time |
Your name and email (user.name, user.email) come first, as in "Git Config: Setting Up Git". The lessons on configuration cover more settings and aliases.
Practices for a Team
Some practices only work when the whole team follows them, so they belong in CONTRIBUTING.md and in the platform's settings:
- One workflow, written down (see "Git Workflows").
- Protected
main: pull requests only, at least one approval, passing checks, no force pushes. - One merge method per repository: merge commit, squash or rebase.
- A commit message convention, such as Conventional Commits, if you generate changelogs from history.
- Small pull requests, reviewed within a day (see "Code Review and Pull Request Etiquette").
- Automated checks on every pull request: build, tests and formatting, with hooks locally and CI on the server (see the lessons on hooks and CI).
Common Mistakes
"WIP" commits on main. Clean them up with interactive rebase or squash before merging.
One giant commit at the end of the week. Impossible to review or partly revert. Commit each finished step.
Fixing conflicts by deleting the other side's work. Read both sides, and ask the author if unsure.
Ignoring git status output. It tells you about untracked files, staged changes and how far you are behind. Read it before every commit and push.
Treating Git as a backup tool only. Commits with good messages are documentation. A history of "update" commits wastes it.
Under the Hood
Most of these practices protect one of two things. Some protect the history, which every clone shares forever: small commits, clear messages, no secrets, no rewriting what others have. Others protect main, the branch everyone builds on: branches per task, reviews, protected branches, checks. Git makes both cheap: commits and branches cost almost nothing, so there is no technical reason to make large commits or long-lived branches. The habits simply use what Git already gives you.
Interview Corner
What are some Git best practices?
Small, focused commits with clear messages; a branch per task, kept short-lived; pull before starting and before pushing; review changes before merging; never commit secrets or generated files (use .gitignore); don't rewrite shared history; force-push only with --force-with-lease; tag releases; protect main.
Why should commits be small and focused?
They are easier to review, understand, revert and cherry-pick, and they make tools like git bisect and git blame far more precise.
What should never be committed to a repository?
Secrets (passwords, keys, tokens), build output, dependency folders, IDE settings and machine-specific files. Use .gitignore from the first commit.
How do you stop tracking a file that was committed by mistake?
Add it to .gitignore, run git rm --cached <file> (it stays on disk), and commit. If it contained a secret, change the secret, because it remains in history.
Practice
Challenge: audit this repository. In the same repository, find three things that break the checklist: commits whose message is a single word, tracked files that look generated, and whether .gitignore covers IDE folders such as .idea/.
What does Git print? Before you open the solution, decide which commit has a one-word message and whether .idea/ is ignored.
Show solution
git log --format=%s | grep -v " " || echo "No one-word messages"
git ls-files | grep -E "\.(class|log)$|^target/" || echo "No generated files tracked"
git check-ignore -q .idea/ && echo ".idea/ is ignored" || echo ".idea/ is not ignored yet"No one-word messages
No generated files tracked
.idea/ is not ignored yetEvery message has more than one word, and no generated files are tracked anymore, after the clean-up. But .idea/ isn't ignored yet: adding .idea/ (and *.iml) to .gitignore is the next small improvement, before anyone opens the project in IntelliJ IDEA.
Checkpoint. Run the same audit on a project of your own, fix what it finds, and write the five practices you find hardest into your team's CONTRIBUTING.md.
Key Takeaways
Quick reference
| Command | It is used to |
|---|---|
git status / git diff --staged | Check before committing |
git add -p | Split changes into focused commits |
git rm --cached <file> | Stop tracking a file committed by mistake |
git check-ignore -v <path> | See whether and why a path is ignored |
git config --global <setting> <value> | Set a default once |
git push --force-with-lease --force-if-includes | Force-push your own branch safely |
Was this tutorial helpful?