I cannot agree it is not possible. By mixing git stash push
, git stash pop
, git checkout
, git checkout
, git add
and git commit
this is possible.
How I understand problem:
You are on branch master and you made some modifications to file patched.txt
and you would like to commit this file to other branch.
What you would like to do is:
- save all changes in this repo by doing git stash
- checkout
file.txt
from stashed stack
- add file
patched
(and only this file) to new branch
- get back to state of repo before modyfing
file.txt
This can be achieved by executing following commands:
destBranch=patch
thisBranch=master
FileToPutToOtherBranch="file1.txt file2.txt 'file with space in name.txt'"
message="patched files $FileToPutToOtherBranch"
#assumption: we are on master to which modifications to file.txt should not belong
git stash &&\ #at this point we have clean repository to $thisBranch
git checkout -b $destBranch &&\
git checkout stash@{0} -- $FileToPutToOtherBranch && #if there are many files, repeat this step #create branch if does not exist (param -b)
git add $FileToPutToOtherBranch &&\ # at this point this is equal to git add . --update
git commit -m "$message" &&\
git checkout $thisBranch &&\
git stash apply &&\ # or pop if want to loose backup
git checkout $thisBranch -- $FileToPutToOtherBranch # get unpatched files from previous branch
The reason why I am using "&&" and the end is if somebody will copy&paste this snippet into terminal, even if one error occurs, next commands will be executed, which is not good. \ is for informing shell that command is continued in next line.
To proove this works I provide testing environment for this snippet
mkdir -p /tmp/gitcommitToAnyBranch && cd /tmp/gitcommitToAnyBranch &&\
git init
echo 'this is master file' > file1.txt
echo 'this is file we do not want to have modified in patch branch because it does not patches any feature' > docs.txt
git add file1.txt && git commit -m "initial commit"
echo 'now this file gets patched' > file1.txt
git status
Now, if you run my script with parameters
destBranch=patch
thisBranch=`git rev-parse --abbrev-ref HEAD`
FileToPutToOtherBranch="file1.txt"
message="patched file $FileToPutToOtherBranch"
You will have file1.txt
modified only in patch branch, for more see gitk --all
develop
instead of the current issue branch. At least thats the reason why I missed that feature ;) – KingCrunch Oct 28 '11 at 18:27git stash
,git checkout develop
, fix your bug,git commit
,git checkout -
and thengit stash pop
so you get your changes back – gustavotkg Oct 28 '11 at 18:31git-new-workir
to make two work trees share the repo via symlinks in .git. – Cascabel Oct 29 '11 at 20:46