Lee Probert Lee Probert - 1 year ago 137
Bash Question

Is there a TRY CATCH command in Bash

I'm writing a Shell script and need to check that a terminal app has been installed. I want to use a TRY/CATCH command to do this unless there is a neater way.

Answer Source

Is there a TRY CATCH command in Bash?


Bash doesn't have as many luxuries as one can find in many programming languages.

There is no try/catch in bash; however, one can achieve similar behavior using && or ||.

Using ||:

if command1 fails then command2 runs as follows

command1 || command2

Similarly, using &&, command2 will run if command1 is successful

The closest approximation of try/catch is as follows

{ # try

    command1 &&
    #save your output

} || { # catch
    # save log for exception 

Also bash contains some error handling mechanisms, as well

set -e

It will immediately stop your script if a simple command fails. I think this should have been the default behavior. Since such errors almost always signify something unexpected, it is not really 'sane' to keep executing the following commands.

And also why not if...else. It is your best friend.