You must commit or stash those changes first before switching branches. You can think of stash as a drawer to store uncommitted changes temporarily. Stashing allows you to put aside the “dirty” changes in your working tree and continue working on other things in a different branch on a clean slate.
git checkout -b your-new-branch
git add <files>
git commit -m <message>
First, checkout to your new branch. Then, add all the files you want to commit to staging. Lastly, commit all the files you just added. You might want to do a git push origin your-new-branch
afterwards, so your changes show up on the remote.
This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.
As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:
git checkout -b branch_name
git add <files>
git commit -m "message"
If you get the error:
error: Your local changes to the following files would be overwritten by checkout:
...
Please commit your changes or stash them before you switch branches
Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:
git stash
git checkout -b branch_name
git stash pop
It will be as if you had made those changes after creating the new branch. Then you can commit as usual:
git add <files>
git commit -m "message"
See the answer by Carl Norum with cherry-picking, which is the right tool in this case:
git checkout <target name>
git cherry-pick <original branch>
See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:
git branch -f <original branch> <earlier commit id>
If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.
If I understand right, you've made a commit to changed_branch
and you want to copy that commit to other_branch
? Easy:
git checkout other_branch
git cherry-pick changed_branch
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