Adventures in Git: Move Commits from `main` to New Branch
by Annika Backstrom in
Adventures in Git, on 1 December 2012.
git
The other night, I sat down with Git to solve what turned out to be a very
simple problem: what if you've started making commits to your main branch, but
want to move your work into a feature branch? After staring at git log
for a
few minutes, I had a forehead-slapping moment. Here's one way to move recent
commits into a branch:
Start with a clean main, based off origin/main:
{ "hash": "a" },
{ "hash": "b" },
{ "hash": "c" }
Make a few commits of your own:
{ "hash": "a" },
{ "hash": "b" },
{ "hash": "c" },
{ "hash": "d" },
{ "hash": "e" },
{ "hash": "f" }
Now, let's move these commits to a branch. Simply create a new branch at the current commit, then reset main back to the state of origin/main.
(main)$ git branch my-feature
(main)$ git reset --hard origin/main
{ "hash": "a" },
{ "hash": "b" },
{ "hash": "c" },
{ "hash": "d", "branch": "feature" },
{ "hash": "e", "branch": "feature" },
{ "hash": "f", "branch": "feature" }
That's all. No git rebase
, no git cherry-pick
, just make your branch and
reset main.