Is it possible to commit a file in a git branch with out checking out that branch? If so how?
Essentially I want to be able to save a file in my github pages branch
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:
file.txt from stashed stackpatched (and only this file) to new branchfile.txtThis 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