bashintermediate

Git Force Push Safely

Use force-with-lease instead of force push to prevent overwriting teammates' commits on remote.

bash
# NEVER use plain --force on shared branches
# git push --force origin main  # DANGEROUS

# Safe force push: fails if remote has commits you haven't fetched
git push --force-with-lease origin feature/my-branch

# Even safer: specify the expected remote ref
git push --force-with-lease=feature/my-branch:abc1234 origin feature/my-branch

# Set force-with-lease as default for force pushes
git config --global alias.pushf "push --force-with-lease"

# Common workflow: rebase then safe force push
git fetch origin main
git rebase origin/main
# resolve any conflicts
git push --force-with-lease origin feature/my-branch

# If force-with-lease is rejected:
# 1. Someone pushed to the remote
# 2. Fetch and review their changes first
git fetch origin
git log origin/feature/my-branch --oneline -5
# 3. Rebase on top of their changes
git rebase origin/feature/my-branch

Use Cases

  • Pushing after rebase without overwriting others' work
  • Updating feature branches after interactive rebase
  • Safe alternative to git push --force

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.