0
0
GitHow-ToBeginner · 3 min read

How to Force Push in Git: Syntax, Example, and Tips

To force push in Git, use the command git push --force or its shorthand git push -f. This command overwrites the remote branch with your local branch, replacing its history.
📐

Syntax

The basic syntax to force push in Git is:

  • git push --force <remote> <branch>: Forcefully updates the remote branch with your local branch.
  • git push -f <remote> <branch>: Short form of the above command.
  • <remote> is usually origin, the default remote repository.
  • <branch> is the branch name you want to push, like main or feature-branch.

Use this command carefully because it overwrites the remote history.

bash
git push --force <remote> <branch>
💻

Example

This example shows how to force push your local main branch to the remote repository named origin. This is useful if you rewrote your commit history locally and want to update the remote branch to match.

bash
git checkout main
# Make some changes and rewrite history, e.g., git rebase or amend commits
git push --force origin main
Output
Enumerating objects: 5, done. Counting objects: 100% (5/5), done. Delta compression using up to 8 threads Compressing objects: 100% (3/3), done. Writing objects: 100% (3/3), 350 bytes | 350.00 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0) remote: Resolving deltas: 100% (1/1), completed with 1 local object. To github.com:user/repo.git + abc1234...def5678 main -> main (forced update)
⚠️

Common Pitfalls

Force pushing can overwrite changes on the remote branch, which may cause others to lose work if they have pulled the previous commits. Avoid force pushing on shared branches unless you coordinate with your team.

Instead of git push --force, consider git push --force-with-lease which checks if the remote branch was updated before overwriting it, making it safer.

bash
git push --force origin main  # Risky: overwrites remote unconditionally
git push --force-with-lease origin main  # Safer: only force pushes if remote unchanged
📊

Quick Reference

CommandDescription
git push --force Force push local branch to remote, overwriting history
git push -f Short form of force push
git push --force-with-lease Force push only if remote branch is unchanged
git push Normal push without overwriting remote history

Key Takeaways

Use git push --force to overwrite remote branch history with your local branch.
Always specify the remote and branch when force pushing to avoid mistakes.
Prefer git push --force-with-lease for safer force pushes that avoid overwriting others' work.
Coordinate with your team before force pushing shared branches to prevent data loss.
Force pushing rewrites history and can cause conflicts if others have pulled the old commits.