gitshellgit-stash

Programmatically get number of stashes in git


My "oldest" stash in a project is something I need to re-apply from time to time. (Yes, there's a reason for this, and yes, it's terrible, but fixing the underlying issue would be more time-consuming than just using git stash for now.)

However, the oldest stash has the highest number in the list, so I can't apply it without first using git stash list to see what number it is.

Is there some way to make Git print the number of stashes it's currently holding, so that something like this would always print the last stash (in a shell supporting this kind of command-interpolation)?

git stash apply $(git stash <count-command>)

I realize I can use something like this:

 git stash list | tail -1 | awk '{print $1}' | grep -oP '\d+'

...but that's pretty hideous, so I'd like to know if there's something simpler.


Solution

  • Given a small sample repository with this stashes:

    > git stash list
    stash@{0}: WIP on foo/master: d9184b5 ...
    stash@{1}: WIP on foo/master: d9184b5 ...
    

    this gives you the number of stash entries:

    > git rev-list --walk-reflogs --ignore-missing --count refs/stash
    2
    

    But you have to substract 1 to get the last entry :-( Thanks to @alfunx that can be done without shell arithmetic:

    > git rev-list --walk-reflogs --ignore-missing --count --skip 1 refs/stash
    1
    

    But to get the oldest stash ref directly you can use this:

    > git log --walk-reflogs --pretty="%gd" refs/stash | tail -1
    stash@{1}
    

    This works in your case, because git stash apply supports both a plain number and stash@{$NUMBER} as an identifier for a stash.