I'd like to write a function that makes it easier to use parameters of the previous command more easily, such as !:1. I've read that in bash this can be accomplished with:
set -o history
set -o histexpand
So how could I write a zsh function that would have access to !:1?
First of, you cannot use
!in ZSH scripts.But there are other ways to access your command line history:
Of course, this does not work from inside a script either as it still tries to access the history, which simply does not exist for non-interactive zsh. But you can incorporate it into a function in your
.zshrcand pass it to a script from there:Calling
histaccesswill retrieve the last command line (fc -l -1), strip the history number (${lastcmd#* }), split it like zsh would (${(z)...}) and pass it tosomescript. Insomescriptyou can do anything further. If you want to use ZSH for scripting please note that arrays begin with1unless the optionKSH_ARRAYSis set, while history expansion begins with0, with!:0being the command name.If you want to avoid filling your history with calls of
histaccess, you can bind it to a key (for exampleAlt+I) in your.zshrc: