How to Force Git Push to Overwrite Files in Remote Repository

John Wachira Feb 02, 2024
  1. the git push Command
  2. Force git push to Overwrite Files in Remote Repository
How to Force Git Push to Overwrite Files in Remote Repository

This article will discuss how to push our local changes to our remote repository and avoid merge conflicts by prioritizing our changes.

We will cover everything you need to know about the git push command. Let’s jump right in!

the git push Command

We use the git push command to publish our local changes to the remote repository. The git push command is the mirror command for the git fetch command.

It exports our local changes to the remote repository as opposed to the git fetch command that imports changes from the remote repository to our local repository.

Here are some common usage options:

  1. The git push <remote> <branch> command will push our local changes from the specified local branch to the remote repository. If the branch does not exist in the remote repository, Git will create the branch and publish our commits.
  2. The git push <remote> --force command will force a push to the remote repository, resulting in a non-fast-forward merge.
  3. The git push <remote> --all command will push all our local branches to the remote repository.
  4. The git push <remote> --tags command will push the tag in our local branches to the remote repository.

Force git push to Overwrite Files in Remote Repository

Sometimes, Git can reject a git push command if the history of the remote repository does not match the history of our local repository. We can force our local revisions to the remote repository using the command below.

git push --force <remote> <branch>

Example:

git push --force origin master

If we do not include <remote> and <branch>, Git will push all local branches with the --set-upstream preset to the remote repository.

Alternatively, you can pull from the remote branch, merge the changes with your local repository and push again. This comes in handy when several developers are sharing the same remote repository.

When the shared commits conflict, we can use the git commit --amend command to fix them. After amending, we can now push the merged changes back to the remote repository.

# Amend
git commit --amend
#Update Commit Message
git push --force origin master

Before we sign off, let’s briefly discuss how to delete a remote branch. This can be useful when we want to do away with a specific branch in our remote repository.

We use the command below to delete a remote branch:

git branch -D <branch-name>
git push origin :branch-name
Author: John Wachira
John Wachira avatar John Wachira avatar

John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.

LinkedIn

Related Article - Git Push