In git, I've been making commits onto the master branch, when really I should have been working on a feature branch. I want to change this so that master is back to where it started, and what was on master is now on a new branch. Basically, my commit history looks like this:
A -- B -- C -- D -- E | | | master origin/master
And I want it to look like this:
master | A -- B -- C -- D -- E | | | new_branch origin/master
How can I change where master points?
Use git branch <branch> to create a new branch at the tip of the current master . Use git reset HEAD~<n> --hard to rewind back <n> commits and discard changes. Use git checkout <branch> to switch to the new branch. Only works if the changes have only been committed locally and not pushed to the remote.
the HEAD is not stepping onto any branch, then above commands do: checkout the target commit (you're already stepping there, but just in case) move master pointer to that commit (no problem, since it is a forward move) checkout master branch in order to be stepping onto it (for future commits)
git stash
git branch new_branch
git reset --hard origin/master
git checkout new_branch
git stash pop
stash/unstash is not necessary if your working tree is clean. just make sure there are no changes in your working tree, because those will be removed when you reset --hard
another possibility (faster, and without the need to stash and reset):
git checkout -b new_branch master
git branch -f master origin/master
$ git checkout master $ git reset --hard <commit-id-for-master-to-sit-at>
for example try this
$ mkdir example; cd example $ git init $ vi testFile.txt (now add "test commit 1" to line 1 of file) $ git add * $ git commit (add message "(+) 1st commit" to git commit) $ vi testFile.txt (now add "test commit 2" to line 1 of file) $ git add * $ git commit (add message "(+) 2nd commit" to git commit) $ vi testFile.txt (now add "test commit 3" to line 1 of file) $ git add * $ git commit (add message "(+) 3rd commit" to git commit) $ git tag final_head $ git reset --hard HEAD~1
this example shows moving the master to a different commit. Note here that the tag allows us to save the old master, in case :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With