You can create an alias for git stash pop or apply that checks for differences from HEAD.
[alias]
pop = !"f() { { git diff-index --quiet HEAD && git stash pop \"$@\"; } || echo \"Can't pop, you have local changes\"; }; f "
apply = !"f() { { git diff-index --quiet HEAD && git stash apply \"$@\"; } || echo "Can't apply, you have local changes"; }; f"
Prefixing with !
, and wraping them in a function call f() { ... }; f "
, allows passing arguments to git stash pop
and git stash apply
.
The command git diff-index --quiet HEAD
will return 0 or 1 depending on whether there are local changes, then the &&
and ||
shortcuts will either continue with the git stash pop/apply, or output an error message.
Wrapping the first part, which uses the &&
shortcut, in braces (so it's { a && b; } || c
) prevents the error message which uses the ||
shortcut firing when the pop or apply fails.
Then you can use git pop
to safely run git stash pop
without interfering with other changes.