I want to stop the zsh script running when it encounters a command not found error.

I know of command_not_found_handler, but this function only allows me to print a message, not halt the parent shell.

The functionality I am looking for is similar to when a glob match fails:

echo nonexistent*
echo this will not be shown
zsh: no matches found: nonexistent*
  • Note that cmd nonexistent* only exits the shell if cmd is builtin. Aug 10 '21 at 12:05
  • set -e / set -o errexit? with all the caveats it has...
    – ilkkachu
    Aug 10 '21 at 12:24
  • @ikkachu I don't want to exit the shell on all errors, just when a command is not found.
    – HappyFace
    Aug 10 '21 at 12:31

You can define a ZERR trap to get finer control than what set -e allows. Conventionally, the exit status 127 is reserved for command-not-found errors.

trap 'if (($? == 127)); then exit 127; fi' ZERR

This has the same caveats as set -e. In particular, it won't trigger inside a conditional such as if no_such_command; …. And it can only exit from the current subshell, not from the original shell (but it will trigger the parent shell's ZERR trap if applicable).

I have a hard time imagining circumstances where the behavior you're asking for would be desirable. Use set -e. For the specific commands where a failure is expected, append || true.

  • If I had known about set -e when I started scripting, I would have used it. Now, however, I would need to refactor tons of stuff to get them to work this way.
    – HappyFace
    Aug 10 '21 at 13:29
  • I have added some code to the zerr trap to ask the user if they want to halt or not; The problem is that the trap is triggered multiple (five) times on a single command not found error. Any ideas?
    – HappyFace
    Aug 10 '21 at 15:20
  • @HappyFace The trap is triggered once per failing command. If you don't understand what your script is doing, post a new question with a small, complete script that reproduces the problem. Aug 11 '21 at 18:56

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.