To stash your changes and move them onto another branch, add this to your .gitconfig:
[alias]
stashonto = "!f() { if [ -z \"$1\" ] ; then echo 'Error: stashonto requires destination branch.\nExample: git stashonto master\nExample: git stashonto -b new-branch 98e7f99e' ; else git stash --include-untracked && git checkout $* && git stash apply ; fi; }; f"
That creates a git alias that calls a shell function so we can chain several git commands. Here's the function broken down so it's easier to read:
f() {
if [ -z \"$1\" ] ; then
echo 'Error: stashonto requires destination branch.\nExample: git stashonto master\nExample: git stashonto -b new-branch 98e7f99e'
else
# stash everything
(git stash --include-untracked
# switch branch
&& git checkout $*
# apply stash (you must 'git stash drop' to delete the stash if everything goes well)
&& git stash apply)
fi
}
f
Warning: It's not fancy enough to detect whether stash saved anything, so if you don't have any changes to stash it will print "No local changes to save" and then apply your previous stash. That's why I'm using apply
instead of pop
.
Usage:
# stash changes and apply on master
git stashonto master
# stash changes and apply on new branch 'project' off of commit 98e7f99e
git stashonto -b project 98e7f99e