How to Push Force Changes in Git
In this article, we will see about pushing local changes forcefully into the remote repository in Git.
Git only allows pushing local changes to the remote repository that are descendants of the changes in the remote repository.
In some cases, we may want to push the changes that are not so (i.e.) changes that may be antecedent to the changes in the remote repository.
We need to use the git push
command with the --force
option in such cases.
We will now illustrate this with an example.
Using git push --force
to Forcefully Push Local Changes in the Remote Repository in Git
Sometimes when working in a collaborative development environment, we encounter a situation when we have pushed some changes in the remote repository.
Now, we decide that those changes are no longer relevant, and we want to push new local changes to the remote repository.
Also, some other team members may have already pulled in those remote repository changes, which we have pushed earlier; and may have worked on top of them. Subsequently, they may have pushed their changes to the remote repository.
Git usually requires that we first pull the changes that may have been pushed by other team members, from the remote repository, before pushing the new local changes into it.
Thus, in such cases, we need to use the git push
command with the --force
option. The syntax of the command is git push origin <branch_name> --force
Suppose, we have a branch named main
. We would then do as follows to push the changes forcefully.
$ git push origin main --force
Caution: This has the effect of overwriting the changes already present on the remote repository that may have occurred since the previous push.
Thus, the changes your team members may have already done on the remote repository will be overwritten.
There is another option for the git push
command viz. --force-with-lease
. Upon using this option with git push
, an error message will be printed, and Git will not push the changes if there are already some changes pushed on the remote repository.
This option --force-with-lease
ensures that we are not overwriting other team members’ changes.