Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop all stashes associated with a particular branch

Tags:

git

I'm in the habit of stashing my changes in git and applying them again with git stash apply. This has the advantage of keeping me from accidentally losing a stash I made, but it also means that my list of stashes grows rather quickly.

When I'm done with a branch, I go back through my stash list and manually remove all of the stashes associated with the branch. Is there a way to do this in a single command?

For example, my current stash list looks like this:

kevin@localhost:~/my/dev/work$ git stash list
stash@{0}: WIP on master: 346f844 Commit comment
stash@{1}: WIP on second_issues: a2f63e5 Commit comment
stash@{2}: WIP on second_issues: c1c96a9 Commit comment
stash@{3}: WIP on second_issues: d3c7949 Commit comment
stash@{4}: WIP on second_issues: d3c7949 Commit comment
stash@{5}: WIP on second_issues: d3c7949 Commit comment
stash@{6}: WIP on second_issues: 9964898 Commit comment

Is there a command that would drop all of the stashes from second_issues?

like image 530
Kevin Avatar asked Jul 10 '13 17:07

Kevin


People also ask

Does deleting a branch delete stashes?

What happens if I stash changes in a branch and then delete that branch? (1) Do I lose the stashed changes? @torek provided an excellent answer, but to be short, a stash entry does not "belong" to any branch, and any branch operations do not affect the stash--it's a completely orthogonal concept.


1 Answers

What about this? It's a quick and dirty way that drops the stashes created on a given branch.

It simply lists all stashes, searches with grep for the stashes created on a branch, gets its stash name and finally passes those names git stash drop through xargs.

git stash list | grep -E 'stash@{[0-9]+}.+ YOUR_BRANCH_NAME' | cut -d ':' -f 1 | xargs git stash drop

Edit

Digging in the man pages, it says the git stash list also accepts git log format options.
So we tell it to print lines that only match YOUR_BRANCHNAME, and of those lines to just print its "reflag identity name" (%gd: shortened reflag selector, e.g., stash@{1}, from the man page).
Then, we pass the output to xargs to drop the stash.

git stash list --grep='YOUR_BRANCHNAME' --format='%gd' | xargs git stash drop
like image 61
Alessandro Vendruscolo Avatar answered Oct 26 '22 04:10

Alessandro Vendruscolo