0

Is it possible to raise exceptions in bash? This can be useful, for example, when we want the script to exit when an error happens in a subcommand. Without exception, it seems the best we can do is to append || exit after each subcommand, which gives poor readability.

I didn't find descriptions about exceptions in bash manual. But I'm wondering whether there are ways to simulate them.

Cyker
  • 9,946
  • 8
  • 65
  • 93
  • Look for `-e errexit` here http://www.tldp.org/LDP/abs/html/options.html – Inian Nov 29 '16 at 05:06
  • @heemayl That looks like a feature specifically design for early aborting. However, the script doesn't abort when a non-last command fails in a pipeline (and this is documented). If the command can raise an exception then things would be different. – Cyker Nov 29 '16 at 05:20
  • @Cyker: You can check a special variable `PIPESTATUS` in `bash` to check if every command on pipe has run properly and break the flow if not running as expected. – Inian Nov 29 '16 at 05:26

1 Answers1

5

No, Bash does not have a notion of exceptions like other languages like Java have. The key unit of error-reporting in Bash is the exit code; functions, commands, and scripts all return 0 on success and non-zero to report some sort of error condition. Many programs document specific exit codes to report certain failure modes, for instance grep uses 1 to mean no-match-found and 2 to report other errors.

There are a number of useful debugging tricks you can take advantage of despite the lack of exceptions, including the caller command which enables some introspection of the current execution context.

Other resources:

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244