keyboard-shortcut
d

git push --force-with-lease

2min read

an image

Don't always use the --force

Once you have re-written your local commit history (with a rebase, git commit --amend, or anything similar), you will most likely need to push this to a remote repository. git prevents you from overwriting history by default. If your changes involved rewriting existing commits then you may need to push with "force". There are a couple of ways to do this:

  • git push - will refuse to work if the histories are not consistent. Effectively, this prevents any commits from ever being re-written. This is the safest option.
  • git push --force-with-lease - only "overwrites" history if the remote repository's branch has not changed since you last fetched it. This means that git won't push if someone else has pushed changes to the branch you want to rebase (usually a team mate!).
  • git push --force - this will update the remote with whatever commits you have locally (regardless of any diverging histories or team contributions). I typically only use this if I am rejecting changes by someone else (not ideal) or if there has been a problem somewhere and my local branch represents the best truth. You shouldn't need to use it often and you should only really use it as a last resort!

I re-write my history quite frequently, so I need to use either --force or --force-with-lease. I favour --force-with-lease in 99% of scenarios and it is effectively my "default" behaviour. Unfortunately, --force-with-lease is longer thatn --force, so I have created an alias on my command line to make it easier to use: alias gpf='git push --force-with-lease'. Now I just need to run gpf to update my remote repository with my re-written history 🚀