How to move a commit to another branch in git
sometimes you can forget to create a branch for a given feature and you have done a lot of work on that branch , so moving commits will save you from manually copying changes.
let say i am working on master
branch and i started adding a feature that need a separate branch but i forgot to create that branch and did the changes on master
, so rather than manually copying the changes to the new branch feature-a
we can easily move the commits of that feature to feature-a
and clean master
git init
touch a.txt
echo hello > a.txt
git add a.txt
git commit -m'hello'
echo 'new feature' > a.txt
git add a.txt
git commit -m'new feature'
git log
commit 17a49036e9b19a0aa4de408e2386139fcab4fdeb (HEAD -> master, feature-a)
Author: slimane amiar <slimaneamiar@talik.io>
Date: Wed Jan 25 06:46:55 2023 +0100
new feature
commit 06ac1512c3f6fafdf084469201cb7c5c40033134
Author: slimane amiar <slimaneamiar@talik.io>
Date: Wed Jan 25 06:46:16 2023 +0100
hello
git checkout -b feature-a
git cherry-pick 17a49036e9b19a0aa4de408e2386139fcab4fdeb
git checkout master
git reset --hard 06ac1512c3f6fafdf084469201cb7c5c40033134
we check the log on feature-a
we see that the commit has moved to it
commit 17a49036e9b19a0aa4de408e2386139fcab4fdeb (HEAD -> feature-a)
Author: slimane amiar <slimaneamiar@talik.io>
Date: Wed Jan 25 06:46:55 2023 +0100
new feature
commit 06ac1512c3f6fafdf084469201cb7c5c40033134 (master)
Author: slimane amiar <slimaneamiar@talik.io>
Date: Wed Jan 25 06:46:16 2023 +0100
hello
if we go back to master
we see that the commit is not on the master
git log
commit 06ac1512c3f6fafdf084469201cb7c5c40033134 (HEAD -> master)
Author: slimane amiar <slimaneamiar@talik.io>
Date: Wed Jan 25 06:46:16 2023 +0100
hello