Git Force Push Safely with --force-with-lease
Learn the difference between git push --force and --force-with-lease. Understand when force pushing is necessary and how to do it safely without overwriting teammates' work.
Detailed Explanation
Safe Force Pushing in Git
Force pushing is sometimes necessary after rebasing or amending commits. But --force can overwrite other people's work. --force-with-lease is the safe alternative.
When You Need to Force Push
- After a
git rebasethat rewrites commit hashes - After a
git commit --amendon a pushed commit - After an interactive rebase (
git rebase -i) - After resetting a branch to a different commit
The Danger of --force
# DANGEROUS: Overwrites remote regardless of its state
git push --force
If a teammate pushed commits after your last fetch, --force silently overwrites their work.
--force-with-lease: The Safe Alternative
# Safe: Only pushes if the remote has not changed since your last fetch
git push --force-with-lease
How it works:
- Git checks if the remote branch is in the state you expect
- If someone else has pushed new commits, the push is rejected
- You need to fetch, integrate the new changes, then push again
Even Safer: Specify the Expected Ref
# Only force push if remote main is at the expected commit
git push --force-with-lease=main:abc1234
Best Practices
- Always use
--force-with-leaseinstead of--force - Set it as an alias:
git config --global alias.pushf "push --force-with-lease" - Communicate with your team before force pushing shared branches
- Never force push main/master -- most teams protect these branches
- Fetch before force pushing to ensure your lease is current:
git fetch origin git push --force-with-lease
What If --force-with-lease Fails?
# Fetch the latest remote state
git fetch origin
# Rebase your changes on top
git rebase origin/your-branch
# Try again
git push --force-with-lease
Use Case
Force pushing is a routine part of rebase-based workflows, where developers rebase feature branches onto the latest main before merging. It is also needed after amending commits that have been pushed to a remote branch. Using --force-with-lease is a best practice adopted by most professional development teams to prevent accidental data loss in collaborative environments.