Git Force Push Safely with --force-with-lease
Learn to force push safely using git push --force-with-lease. Protect against overwriting teammates' work while updating remote branches.
git push --force-with-leaseDetailed Explanation
Why Force Push?
After rebasing or amending commits on a feature branch, the local and remote histories diverge. A normal git push will be rejected. You need to force push — but doing so carelessly can overwrite teammates' work.
The Danger of --force
# DANGEROUS: Overwrites remote regardless of its state
git push --force
If a teammate pushed commits after your last fetch, --force will silently destroy their work.
The Safe Alternative: --force-with-lease
# SAFE: Only pushes if the remote hasn't changed since your last fetch
git push --force-with-lease
--force-with-lease checks that the remote branch is at the commit you expect. If someone else has pushed in the meantime, the push is rejected, and you must fetch and reconcile first.
How It Works
- Git stores the expected state of the remote ref when you last fetched.
- On push, Git compares the actual remote ref to the expected one.
- If they match, the push proceeds.
- If they differ, the push is refused with an error.
Best Practices
# Always fetch before force pushing
git fetch origin
git rebase origin/main
git push --force-with-lease
Setting as Default
You can configure Git to always use --force-with-lease when force pushing:
git config --global alias.fpush "push --force-with-lease"
When Force Pushing Is Acceptable
- On your own feature branches after rebasing or amending.
- On branches where you are the sole contributor.
- Never on
main,develop, or any shared integration branch.
The golden rule: if anyone else might be working on the branch, use --force-with-lease. It is a one-word insurance policy against destroying someone else's work.
Use Case
After rebasing a feature branch onto the latest main, a developer needs to update the remote branch. They use --force-with-lease to ensure they do not overwrite a teammate's recent push.