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?

  • 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, 2019 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 Apr 25, 2019 at 9:33

1 Answer 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$ :
<no command> last was <:>
zsh$ pwd

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.