Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

I learned about a new git push command line flag – --force-with-lease. 😲 Learn what it's about!

After working with git for years, I feel comfortable with using it. I manage to squash commits, change the last commit or rebase things on the command line without getting too nervous.

When you apply a lot of git magic rewriting a repo's git history, you might approach the point where you have to force push to a remote branch because it refuses to accept your git foo.

# lots of git magic followed by:

$ git push origin foo --force 
# ☝️ will update the remote no matter what

But performing git push with the --force flag can be brutal. It overwrites the remote branch with your local version without any additional checks or asking for permission. When you're working with other people on the same branch, it can quickly happen that you overwrite commits done by your team members.

Think of the following example:

  • you do a git pull to get the latest changes
  • you do some git magic, but it takes a while
  • you force push your changes

Suppose, another coworker pushes new changes to the remote in the meantime.

Now, you'll overwrite these with your force push without knowing.

The --force-with-lease can help to avoid this desaster because it won't update the remote branch when it isn't in a known state.

# lots of git magic followed by:

$ git push origin foo --force-with-lease
# ☝️ can still be rejected when
# someone updated the branch upstream

There a few more minor things to know about --force-with-lease and Steve Smith wrote an excellent article on the whole topic. I recommend to check that one out. ;)

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles