bashintermediate
Git Force Push Safely
Use force-with-lease instead of force push to prevent overwriting teammates' commits on remote.
bashPress ⌘/Ctrl + Shift + C to copy
# 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.
bashbeginner
Rename Git Branch (Local and Remote)
Commands to rename a local and remote Git branch including updating tracking references.
Best for: Fixing branch naming convention mistakes
#git#branch
bashbeginner
Git Remote Prune and Branch Cleanup
Clean up stale remote-tracking branches and local branches that have been merged or deleted upstream.
Best for: Keeping local repository tidy
#git#cleanup
bashintermediate
Git Hooks Pre Commit
Git workflow: git-hooks-pre-commit
Best for: version control
#git#version-control
bashadvanced
Git Hooks Post Commit
Git workflow: git-hooks-post-commit
Best for: version control
#git#version-control