Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

git stash drop oldest stashes ( say oldest 5 stashes)

Tags:

git

git-stash

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}
like image 406
RajKon Avatar asked Jan 07 '23 23:01

RajKon


2 Answers

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 stashes
  • cut -f 1 -d: Select only the first column (stash identifier, for example stash@{29})
  • tail -5: Keep only the last five lines
  • sort -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.

like image 151
user3159253 Avatar answered Jan 17 '23 15:01

user3159253


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
like image 23
lacostenycoder Avatar answered Jan 17 '23 15:01

lacostenycoder