When using Git one inevitably find himself in a position when some work is unfinished yet you need to switch to working on a more urgent change.
What do you with the code that’s work in progress? You don’t want to lose what you have started, yet it’s untested, not ready to be committed and will need refactoring?
Git has a Stash feature that allows you to stash your changes aside and go back to the clean working directory.
You can unstash the old work back into the working directiry when you are ready to finish it.
Some useful Stash commands are listed below.
To stash some work aside
git stash save "a message"
To list the stashed modifications
git stash list
Stash Example
Stash aside your work, add a message to remember what it was:
$ git stash save "stash at 10:41" Saved working directory and index state On master: stash at 10:41 ~/ (master) $ git status On branch master nothing to commit, working tree clean
/proj1 (master)
$ git stash list
stash@{0}: On master: stash at 10:41
You do some more work, and maybe you get interrupted again – so stash again:
$ git stash save "stash at 10:44"
Saved working directory and index state On master: stash at 10:44
/proj1 (master)
$ git stash list
stash@{0}: On master: stash at 10:44
stash@{1}: On master: stash at 10:41
To show files changed in the last stash
$ git stash show notes.txt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-)
So, to view the content of the most recent stash, run
$ git stash show -p diff --git a/notes.txt b/notes.txt index 50b5162..b168564 100644 --- a/notes.txt +++ b/notes.txt @@ -1 +1,3 @@ ---- start notes \ No newline at end of file +--- start notes + +new work \ No newline at end of file
To view the content of an arbitrary stash, run something like this (shows diff, but no untracked files)
git stash show -p stash@{1}
if you used git stash save –include-untracked, and you want to show untracked stashed files (hack that depends on your git version to work):
git ls-tree -r stash@{0}^3
when ready to go back to the stashed work – pop the stashes one by one:
git stash pop
$ git stash list
stash@{0}: On master: stash at 10:41
Lastly, a quick comand about pull requests workflow
If you have manual pull request workflow and want to email someone your code changes, you can follow the Pre-commit workflow:
- Commit change to local repo
- Extract it as a diff:
# to a file
git format-patch HEAD~1
# or to std out
git format-patch HEAD~1 --stdout
- E-mail outputted path to the owner of the repo, for example use git send-email command to send it to the email list for review
- Recipient applies the patch via git apply or git am