In Git, git push –force and git push –force-with-lease are both commands that can be used to force-push changes to a remote repository. However, there is an important difference between these two commands.
git push –force overwrites the remote branch with your local branch, regardless of whether there have been any changes made to the remote branch since your last pull. This can be dangerous if you are collaborating with others, as it can result in the loss of their changes.
git push –force-with-lease, on the other hand, will only force-push changes to the remote branch if the remote branch matches the local branch. If there have been any changes made to the remote branch since your last pull, Git will reject the push and display an error message. This can help to prevent the loss of other collaborators’ changes.
Here’s an example to illustrate the difference between these two commands:
Alice and Bob both clone a Git repository and make changes to the same file.
Alice commits her changes and pushes them to the remote repository:
# Alice commits her changes and pushes them to the remote repository
git add <file>
git commit -m "Alice's changes"
git push
Bob also commits his changes and tries to push them to the remote repository using git push –force:
# Bob commits his changes and force-pushes them to the remote repository
git add <file>
git commit -m "Bob's changes"
git push --force
Because Bob used git push –force, his changes overwrite Alice’s changes, resulting in the loss of Alice’s work.
# Alice's changes are lost
git log
commit 1234 (HEAD -> master)
Author: Bob
Date: 2022-03-20 12:00:00 +0800
Bob's changes
If Bob had used git push –force-with-lease instead, Git would have detected that the remote branch had been updated since Bob’s last pull and would have rejected the push. This would have prevented the loss of Alice’s changes.
In summary, git push –force and git push –force-with-lease are both commands that can be used to force-push changes to a remote repository. However, git push –force overwrites the remote branch regardless of whether there have been any changes made to the remote branch since your last pull, while git push –force-with-lease will only force-push changes if the remote branch matches the local branch. It is generally recommended to use git push –force-with-lease to prevent the loss of other collaborators’ changes.