Working with a version control system like Git is very much useful for any software developer.
In certain scenarios, you’re permitted to write access to the original remote upstream git repository when you’re provided with project management tools by ZenHub or similar tools.
While working on forked repository having to write access to the original remote repository, there are chances that you might have accidentally pushed commits to the original repository which you shouldn’t be.
This is some time which is risky to merge accidentally a piece of code directly to the original repository.
I’ve also accidentally pushed some accidental commit to the upstream repository. So, I was always looking for some workarounds to prevent accidental remote push in Git.
I’ve come across a better solution that will prevent you from pushing accidental commits to your upstream repository.
Before proceeding further, let me clarify some terminology with you:
- origin – the forked repository
- upstream – the original repository
As shown in the screenshot (1), you can check the list of remotes with fetch and push capabilities to identify which remote push you want to disable.
git remote -v

In this case, I want to prevent remote push to upstream and replace it with the origin so that whenever I accidentally push to remote upstream then Git will understand and push those changes to origin instead of upstream.
How to prevent accidental remote push to upstream?
You need to execute remote push set URL git command to prevent or disabled accidental remote push.
In general,
git remote set-url --push {remote} {url}
For example, I’ve implemented the command to push to remote origin even if I’ve accidentally used the command to push remote upstream.
git remote set-url upstream https://github.com/mehul0810/wp-cli.git
where upstream is my remote and URL is my forked repository of wp-cli

Now, executing the remotes list command will show you the updated git remotes list as per the screenshot (3).

Do It Yourself – Accidental Commit Prevention
Do some code changes and commit the code. Now, push that commit to upstream as per the screenshot (4).
git push upstream

But, when Git will process the command, it will show you that the commit is pushed to remote origin instead of remote upstream.
Hence, whenever you’ll accidentally push commit to upstream it will always go to your origin.
Stay Safe!
Conclusion
This guide to accidental git remote push will help you be at the safer side when you’re provided the write access to the original repository.
There are chances of messing up the original repository due to accidental pushing of commits to remote upstream which can lead to loss of valuable data and lots of rework.
P.S. Please feel free to share this Git Trick to your friends/colleagues.