Using Git, I want to stash only one hunk in one specific file in order to commit the rest of the changes. Therefore, I could go back to my temporary change by pulling it from stash. However, the only way I could find is to stash the whole unstaged files.
Here is a workflow that accomplishes what you want using a branch, which is personally what I prefer to use instead of the stash. It's more typing and more commands, but it gives you full control of the results afterwards.
git checkout -b dev.temp
git add <file-to-stash>
git commit -m'stash work alike'
git checkout <base-branch>
# commit what you need in <base-branch>
From here you have your "stashed" file in a branch so there are many ways to continue.
Option 1: go the the branch and keep working there, with a merge or rebase when you're done:
git checkout dev.temp
git rebase <base-branch>
#work here, merge or rebase when you're done
Option 2: check out the file into your main branch:
git checkout dev.temp <file-to-stash>
<file-to-stash> is now in the index; use git reset to revert it to a locally changed file and keep working where you were at.
Option 3: cherry pick the commit so it's also committed in your working branch - this is the least like your workflow, however, since it leaves <file-to-stash> committed in `, but here it is for completeness:
git cherry-pick dev.temp
With all options, you can delete the branch with git branch -D dev.temp when you're done with it. -d will do if you actually merged it back in, but -D is needed if the branch is not actually merged but you have recovered the changes you wanted.
I have a strong preference for using temporary dev branches over the stash because it gives you a lot more control over what you put in and how you take it back out afterwards, although I agree there are also effective (and certainly quicker) workflows with the stash itself: it's a trade-off between speed and control.
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