RajKon RajKon - 4 years ago 204
Git Question

git stash drop oldest stashes ( say oldest 5 stashes)

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}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download