Commit to another branch without touching unstaged files
I have two branches, say B1 and B2. I’m in B2 and I have staged and unstaged files.
I want the staged files to be committed in B1 (I thought I was in B1 when I
git add-ed the files) and the unstaged ones to be committed in B2.
Is it possible? How?
3 Solutions collect form web for “Commit to another branch without touching unstaged files”
git stash is really powerful when it comes to move dirty changes between branches. In your case, you can apply these steps:
git stash --keep-index, this will stash only unstaged files
git stash, this will stash the rest, i.e. staged files
- switch to B1
git stash pop, staged files will be moved to B1
- switch to B2
git stash pop, unstaged files will be moved to B2
After that, you can commit the changes in each branch individually.
I’m sure there’s a more elegant way but all I could come up with is:
- Commit staged files to B2
- Stash the unstaged work on B2
- Switch to B1, then cherry-pick the latest commit of B2 in B1
- Switch back to B2, reset the latest commit (–hard way)
- Stage and commit the stashed work on B2
This question has a detailed answer that does more or less what I’ve suggested.
If the modfied staged and unstaged files does not change by switching to branch B1, you can switch branches without affecting anything, then you can easily commit your files and switch back to B2.
However if your modified files are changed between B1 and B2, you cannot switch branches. In this case, you have to stash your changes before swithcing branches.
git stash --keep-indexto stash and keep staged files
git reset HEADto unstage staged files
git stashto stash your previousely staged files
git checkout B1to switch to B1 branch
git stash popto unstash and remove your last stash
git commit -ato commit your previousely staged files on B1
git checkout B2to switch to B2 branch
git stash pop
git commit -acommit all the remaining changes on B2
Be carefull with these commands! I’m not a git pro! 🙂