Search code examples
zshzsh-alias

How do I access the last command from a zsh function?


I'd like to do something like this:

function invim () {
  vim $(!!)
}

However when I run it, it says: invim:1: command not found: !!

I assume this is because !! is an interactive shell expansion not available in noninteractive scripts/functions. In bash I could use the history command to accomplish this, but when I tried to use it, it seems to hijack my readline and not allow up-arrow completion to work anymore.

Any help is appreciated!


Solution

  • Using Gairfowl's answer with the associative array, I was able to formulate an appropriate solution:

    function invim {                                              
        vim $(bash -c ${history[@][1]})            
    }
    

    Here's how it works:

    1. ${history[@][1]} is the text of the latest command, for example, find . -type f -name "*.txt"
    2. Run that command in a shell using bash -c
    3. The resulting stdout is captured by the enclosing $(), and is then passed to vim as the filename(s) to edit. There are no enclosing quotes here to allow for multiple line outputs to all be opened.