Wednesday, 31 May 2017

shell - 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




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 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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...