Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mistakenly committed to master locally. How to move changes to branch? [duplicate]

Tags:

git

branch

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?

like image 453
Dov Avatar asked Dec 05 '22 11:12

Dov


1 Answers

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:

  1. create new branch with your commits on it
  2. "re-wind" other branch so the commits are not on it
  3. push branches to remote (if necessary, using -f)
like image 129
Teknikal_Domain Avatar answered Jan 20 '23 09:01

Teknikal_Domain