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.

Remote

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 rebase that rewrites commit hashes
  • After a git commit --amend on 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:

  1. Git checks if the remote branch is in the state you expect
  2. If someone else has pushed new commits, the push is rejected
  3. 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

  1. Always use --force-with-lease instead of --force
  2. Set it as an alias:
    git config --global alias.pushf "push --force-with-lease"
    
  3. Communicate with your team before force pushing shared branches
  4. Never force push main/master -- most teams protect these branches
  5. 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.

Try It — Git Command Reference & Cheat Sheet

Open full tool