Git Force Push Safely
Use force-with-lease instead of force push to prevent overwriting teammates' commits on remote.
# 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-branchUse 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.
Rename Git Branch (Local and Remote)
Commands to rename a local and remote Git branch including updating tracking references.
Undo Last Git Commit (Soft and Hard)
Git commands to undo the last commit while keeping changes staged, unstaged, or fully discarded.
Git Rebase Workflow Example
Step-by-step git rebase workflow to keep feature branches up to date with main branch cleanly.
Git Cherry-Pick Commits Example
Apply specific commits from one branch to another using cherry-pick with conflict resolution.