Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception handling in shell scripting?

I'm looking for exception handling mechanism in shell script. Is there any try,catch equivalent mechanism in shell script ?

like image 906
Mandar Pande Avatar asked Aug 05 '11 19:08

Mandar Pande


People also ask

Is there try catch in shell script?

There is no try/catch in bash; however, one can achieve similar behavior using && or || . it stops your script if any simple command fails.

Does bash have error handling?

Let your Bash script help you find its errors with error handling. Scripting is one of the key tools for a sysadmin to manage a set of day-to-day activities such as running backups, adding users/groups, installing/updating packages, etc.

How do you throw a bash script error?

When you raise an exception you stop the program's execution. You can also use something like exit xxx where xxx is the error code you may want to return to the operating system (from 0 to 255). Here 125 and 64 are just random codes you can exit with.


1 Answers

There is not really a try/catch in bash (i assume you're using bash), but you can achieve a quite similar behaviour using && or ||.

In this example, you want to run fallback_command if a_command fails (returns a non-zero value):

a_command || fallback_command 

And in this example, you want to execute second_command if a_command is successful (returns 0):

a_command && second_command 

They can easily be mixed together by using a subshell, for example, the following command will execute a_command, if it succeeds it will then run other_command, but if a_command or other_command fails, fallback_command will be executed:

(a_command && other_command) || fallback_command 
like image 161
mdeous Avatar answered Sep 30 '22 21:09

mdeous