Is there a TRY CATCH command in Bash

Is there a TRY CATCH command in Bash?

No.

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 stops your script if any simple command fails.

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

Leave a Comment