0

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?

tripleee
  • 175,061
  • 34
  • 275
  • 318
ian
  • 234
  • 2
  • 9
  • You cannot use history expansion inside scripts in Bash, either; it's exclusively an interactive feature. – tripleee Dec 31 '13 at 06:57
  • That's too bad, but if that's the answer there's no way around it. If you post it as an answer I'll accept it – ian Jan 01 '14 at 08:40
  • @tripleee No, it's only on by default in interactive `bash` shells. The two `set` commands in the question enable it in non-interactive shells as well. – chepner Jan 03 '14 at 17:29

1 Answers1

1

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
Adaephon
  • 16,929
  • 1
  • 54
  • 71