Haldean Brown
Haldean Brown

Reputation: 12721

"Exception handling" in shell scripts

I know that you can use the shortcutting boolean operators in shell scripts to do some sort of exception handling like so:

my_first_command && my_second_command && my_third_command

But this quickly becomes unreadable and unmaintainable as the number of commands you want to chain grows. If I'm writing a script (or a shell function), is there a good way to have execution of the script or function halt on the first nonzero return code, without writing on one big line?

(I use zsh, so if there are answers that only work in zsh that's fine by me.)

Upvotes: 5

Views: 1423

Answers (1)

Greg Hewgill
Greg Hewgill

Reputation: 993941

The -e option does this:

   ERR_EXIT (-e, ksh: -e)
          If a command has a non-zero exit status, execute the ZERR  trap,
          if set, and exit.  This is disabled while running initialization
          scripts.

You should be able to put this on the shebang line, like:

#!/usr/bin/zsh -e

Most shells have this option, and it's usually called -e.

Upvotes: 6

Related Questions