Git·19 questions

What to do if you pushed to the wrong branch?

Answer

Pushing to the wrong branch is a common mistake. Actions depend on whether you noticed immediately and whether others have already pulled.

Situation

push to your feature branch, but commits should be in another. Create the correct branch from the current state: git branch correct-branch. Switch to it: git checkout correct-branch. Now the commits are in the correct branch. Remove the wrong commits from the original branch: git checkout wrong-branch, git reset --hard origin/wrong-branch (returns to the remote state before your push), git push --force-with-lease. Then push the correct branch: git checkout correct-branch, git push -u origin correct-branch.

Situation

push to a shared branch (main, develop). If the commits are small and no one has pulled yet, you can revert via git revert. Switch to main: git checkout main. Create revert commits: git revert HEAD~2..HEAD (if you pushed 2 commits). Push: git push. This is safe — history is not rewritten, revert commits are added.

Situation

push contained secrets (passwords, keys). A simple revert is not enough — secrets remain in history. You need to rewrite history: git reset --hard <commit-before-secret>, git push --force-with-lease. Then обязательно rotate the leaked secrets — change passwords, reissue keys. Even after force-push, secrets remain in reflog and cached Git objects on the server for 90 days. For full cleanup, use BFG Repo-Cleaner or git filter-repo. On GitHub: contact support to remove cached copies.

Situation

several developers have already pulled your erroneous branch. Don't force-push — it will break their local repositories. Use git revert — create revert commits and push. The team will get the revert via pull, and the erroneous changes will be undone for everyone.

Prevention: set up branch protection on GitHub — forbid direct push to main. Use pull requests for all changes. Before push, check the current branch: git branch — the asterisk shows the current one.

Was this answer helpful?

More questions in this topic

Related questions from other topics