Search code examples
gitgit-stash

Alias: `git pop last`, for `git stash pop [last stash on the list]`


Is this even possible? I want an easier command to git stash pop stash@{13} where stash@{13} would simply be last meaning "the last stash on the list" or "the oldest stash".

I know I can create an alias of git pop for git stash pop (which I could use like git pop stash@{13}), but I'd like something simpler like git pop last. Would I need to write my own script or is there a way to do it just with git or alias? I use Windows primarily but sometimes Linux.


Solution

  • Building off the hints provided by @torek, this should get you the ref of the stash you want:

    git reflog stash -- 2> /dev/null | tail -n 1 | cut -d ' ' -f 2 | cut -d ':' -f 1
    

    The -- ensures you are looking for a revision rather than a path. The 2> /dev/null suppresses errors in case there are no stashes.

    An alternative that avoids using cut (again suggested by @torek) is:

    git log --walk-reflogs --format=%gd stash -- 2> /dev/null | tail -n 1
    

    Thus, you can set your alias like this:

    git config alias.pop-last "! git stash pop $(git reflog stash -- 2> /dev/null | tail -n 1 | cut -d ' ' -f 2 | cut -d ':' -f 1)"
    

    Or:

    git config alias.pop-last "! git stash pop $(git log --walk-reflogs --format=%gd stash -- 2> /dev/null | tail -n 1)"
    

    Either of these commands will give you a nice error of No stash found. if there is none found.

    I've tested and this works in the Git Bash prompt on Windows. (It should also work in Linux.)