Bash does not natively support a try/catch syntax for errors; however, there are options for handling errors within a script.
Try and Catch errors in Bash
For the first technique, simply detect if there’s a non-zero status by using the following syntax:
|
|
In addition, an ||
(or) expression may be used instead:
|
|
For explicitness, the full syntax for a try/catch
in Bash is:
|
|
If command_call
is not successful, the echo statement will be invoked in all scenarios.
Error handling in Bash
For the second technique, bash
provides a native variable for reporting exit codes: $?
. Some users may want to catch and handle specific exit codes.
|
|