How can I use ! expansion in a ZSH script?

382 Views Asked by At

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?

1

There are 1 best solutions below

0
On

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