How do I drop oldest stashes (say oldest 5 stashes) in one statement instead of doing something like this:
git stash drop stash@{3}
git stash drop stash@{4}
git stash drop stash@{5}
git stash drop stash@{6}
git stash drop stash@{7}
Thanks to an anonymous user's edit, the correct command would look like this:
git stash list | cut -f 1 -d : | tail -5 | sort -r | xargs -n 1 git stash drop
Here's his/her explanations:
git stash list
: List all your stashescut -f 1 -d
: Select only the first column (stash identifier, for example stash@{29})tail -5
: Keep only the last five linessort -r
: Invert the order of the lines to drop the oldest stash first (otherwise remaining stashes get new names after each removal)xargs -n 1 git stash drop
: For each line transmitted in the pipe, execute git stash drop, since git stash drop
[may] support only one stash a time.All kudos to the mysterious stranger.
The accepted answer is great. And if you may use it often, you can add it to a shell function like this which would take an argument for number of old stashes you want to remove:
git-stash-prune() {
git stash list | cut -f 1 -d : | tail -"$1" | sort -r | xargs -n 1 git stash drop
}
Then you can call it like this for example would delete the last 10 stashes.
git-stash-prune 10
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