I made a number of changes that could break the code. I thought I was in a branch but was in master when I committed. Is there any way to move the 4 local commits to a branch locally and then push?
Asked
Active
Viewed 1.5k times
3 Answers
16
Going by the details you said (4 commits), you could do this:
git branch new-branch-name-here
# new commits on branch
git checkout master
git reset HEAD~4
# move HEAD (master) 4 commits back, commits are no longer on master
# note: that's a ~ (tilde, above your Tab), not a - (dash).
git push origin new-branch-name-here
# push new branch with correct commits to remote (assumed origin)
git push -f origin master
# if you already pushed master before, clear commits from remote
# otherwise, this can be skipped if master wasn't yet pushed remotely
The -f
for pushing master
is required, otherwise your push will get rejected by the server.
In general, changing commits on a branch in Git can be done in three easy steps:
- create new branch with your commits on it
- "re-wind" other branch so the commits are not on it
- push branches to remote (if necessary, using
-f
)

Teknikal_Domain
- 318
- 1
- 11
-
1He never mentioned that he pushed those commits. No need for a risky `push -f`. – pepece Dec 03 '21 at 08:49
8
You may also try
git reset HEAD~
This will revert the local commit and restore the changes. And then create a new branch, commit and push your changes over there.
-
1This worked for me as I just needed a fresh start on the repo (and I'm not using rebase). Although I needed to add --hard. Simplicity FTW. – Erez Cohen Feb 05 '19 at 11:44
3
You should be able to just create your new branch, and then reset master
back to the correct commit.
git branch oopsies-feature-branch
git branch -f master THE_RIGHT_COMMIT_FOR_MASTER

CollinD
- 7,304
- 2
- 22
- 45