Force a Git Push

How do I properly force a Git push?

I’ve been working with Git for a few years now, and to properly force a Git push, you can use the following commands:

For a specific branch:


git push origin <your_branch_name> --force

For a specific repository:


git push https://git.... --force

These commands will overwrite your previous commits with your current ones.

For simplicity, you can also use the short flag -f instead of --force:


git push origin <your_branch_name> -f

Just a word of caution, though—forcing a push will delete your previous commits and push your current ones, so use it with caution.

Adding to what Alveera mentioned, with my experience in managing repositories, I highly recommend the following practices:

  1. Push only to the main repository.

  2. Ensure that the main repository is a bare repository to avoid any issues with the working tree being out of sync with its .git base. For more details, see ‘How to push a local git repository to another computer?’

  3. If you need to make modifications in the main (bare) repository, clone it on the main server, make your changes, and then push them back.

In summary, maintain a bare repository accessible from both the main server and your local computer to have a single upstream repository for pulling and pushing changes.

Shilpa’s points are spot on. From my experience, especially with corporate environments, here’s our solution for replacing the master branch on a corporate GitHub repository while preserving history.

Since force-pushing to the master branch on corporate repositories is often disabled to maintain branch history, we used this approach:


git fetch desiredOrigin

git checkout -b master desiredOrigin/master # Fetch and checkout the origin's master branch

git checkout currentBranch # Switch to the target branch

git merge -s ours master # Merge using the 'ours' strategy over master

# Edit the commit message in the text editor that opens (e.g., vim)

git checkout master # Switch back to the master branch

git merge currentBranch # Merge the resolved changes into master

This method allowed us to update the master branch while maintaining the branch history.