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
.zshrc
and pass it to a script from there:Calling
histaccess
will retrieve the last command line (fc -l -1
), strip the history number (${lastcmd#* }
), split it like zsh would (${(z)...}
) and pass it tosomescript
. Insomescript
you can do anything further. If you want to use ZSH for scripting please note that arrays begin with1
unless the optionKSH_ARRAYS
is set, while history expansion begins with0
, with!:0
being 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
: