First of, you cannot use !
in ZSH scripts.
But there are other ways to access your command line history:
$ echo foobar
foobar
$ fc -l -1
501 echo foobar
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:
function histaccess ()
{
lastcmd=$(fc -l -1)
somescript ${(z)${lastcmd#* }}
}
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 to somescript
. In somescript
you can do anything further. If you want to use ZSH for scripting please note that arrays begin with 1
unless the option KSH_ARRAYS
is set, while history expansion begins with 0
, 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 example Alt+I
) in your .zshrc
:
zle -N histaccess
bindkey '^[i' histaccess