2

I'm using snippet code below to exclude all failed commands (return code 1) from saving to zsh history:

 zshaddhistory() { whence ${${(z)1}[1]} >| /dev/null || return 1 }

But if the command is an alias lsl (alias lsl='ls -l') the failed command will still be inserted into zsh history:

lsl whatever_folder_doesnt_exist

whatever_folder_doesnt_exist doesn't exist and I observe lsl whatever_folder_doesnt_exist still in zsh history.

Here I want to exclude all command that return code is not 0, how can I do that?

Tuyen Pham
  • 1,805

1 Answers1

1

You can use the zsh-hist plugin to set up a precmd hook that deletes the last item from history, if it had a non-zero exit status:

source path/to/zsh-hist.plugin.zsh
delete-failed-history() {
  (( ? )) && 
    hist -s d -1
}
autoload -Uz add-zsh-hook
add-zsh-hook precmd delete-failed-history

If you want that it deletes only commands that have exit status 1 exactly, then change (( ? )) to (( ? == 1 )).

  • Unfortunately this makes it impossible to correct the command, since the failed command line can't be restored by pressing the up arrow anymore. – Silvan Mosberger Oct 24 '22 at 20:39
  • It’s possible to automatically load the faulty command into the command line, so you can fix it. That wasn’t what asked, though. If you want me to tell you how to do that, feel free to open a new question. – Marlon Richert Oct 25 '22 at 03:19