1

Imagine I am typing at my terminal prompt, but actually decide not to type anything. Instead I just press enter.

Is there a way I can make zsh run a command now?

I want to potentially make this command variable, e.g. repeat the last command, or if the last command was z then pressing enter on the blank prompt should run echo $PWD.

How can I do this?

2
  • you might find some options with superuser.com/a/625663/513541, although I'd point out that "an empty command" is vastly different than the non-empty command "z". I, myself, struck out on the TRAPDEBUG() route -- an empty command seems not to trigger it. – Jeff Schaller Apr 25 '19 at 1:35
  • @JeffSchaller I meant that if I run z it takes me to a directory, and then pressing enter (on the now blank command line, re-drawn prompt) it should run my specified echo $PWD – theonlygusti Apr 25 '19 at 9:33
1

You can try using the preexec and precmd hooks:

preexec(){ cmd=$1; }
precmd(){ if [ "$cmd" ]; then lcmd=$cmd; cmd=; else; echo "<no command> last was <$lcmd>"; fi; }

zsh$ :
zsh$
<no command> last was <:>
zsh$ pwd
/home2/ahq

You should read the whole thing in the Hook Functions subsection in the zshmisc(1) manpage, especially the part about the arguments which are passed to preexec.

Also, instead of defining the hook functions directly, you can use add-zsh-hook:

autoload -Uz add-zsh-hook
add-zsh-hook -Uz precmd my_precmd

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.