Skip to content

How to Git Force Push Safely

DodaTech 2 min read

In this tutorial, you'll learn about How to Git Force Push Safely. We cover key concepts, practical examples, and best practices.

The Problem

You try to push a branch after rebasing and get:

 ! [rejected]        main -> main (non-fast-forward)
error: failed to push some refs to 'github.com:user/repo.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally.

A regular git push fails because your local and remote histories have diverged. A force push would overwrite the remote, but a raw git push --force is dangerous -- it can delete other people's commits.

Quick Fix

Step 1: Use --force-with-lease

git push --force-with-lease origin main

This checks that the remote branch is still at the commit you expect. If someone else pushed to the same branch, the push is rejected.

Step 2: If --force-with-lease fails

git fetch origin
git rebase origin/main
git push --force-with-lease origin main

This pulls the latest changes, rebases your work on top, then force-pushes safely.

Step 3: Verify after push

git log --oneline origin/main -5

Expected output shows your commits at the top.

Alternative Solutions

If you must use --force, use --force-if-includes for extra safety:

git push --force-if-includes origin main

Or use git push --force with explicit refspec:

git push origin +main

The + prefix means force push that specific branch.

Practice with a Test Repository

cd /tmp
mkdir git-practice && cd git-practice
git init --initial-branch=main
# Initialized empty Git repository in /tmp/git-practice/.git/
echo "test" > file.txt && git add . && git commit -m "init"
# [main (root-commit) abc1234] init

Before running destructive commands on your real repository, practice on a throwaway test repository. This builds confidence and prevents costly mistakes. The reflog is your safety net, but practice makes it less needed.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Prevention

  • Configure git push --force-with-lease as an alias: git config --global alias.pushf "push --force-with-lease".
  • Never force push to shared branches like main or develop.
  • Use pull requests with branch protection rules.
  • Communicate with your team before rewriting shared history.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro