git stash drop oldest stashes ( say oldest 5 stashes)

北战南征 提交于 2019-12-21 05:39:09

问题


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}

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/34345691/git-stash-drop-oldest-stashes-say-oldest-5-stashes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!