Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing try catch finally in shell

Is there a linux bash command like the java try catch finally? Or does the linux shell always go on?

try {    `executeCommandWhichCanFail`    mv output } catch {     mv log } finally {     rm tmp } 
like image 945
Jetse Avatar asked Mar 27 '13 10:03

Jetse


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.

Is there a try catch in bash?

The bash shell does not have any fancy exception swallowing mechanism like try/catch constructs. Some bash errors may be silently ignored but may have consequences down the line.

What does || mean in shell script?

Logical OR Operator ( || ) in Bash The logical OR operator || processes multiple values. It is usually used with boolean values and returns a boolean value. It returns true if at least one of the operands is true. Returns false if all values are false.


1 Answers

Based on your example, it looks like you are trying to do something akin to always deleting a temporary file, regardless of how a script exits. In Bash to do this try the trap builtin command to trap the EXIT signal.

#!/bin/bash  trap 'rm tmp' EXIT  if executeCommandWhichCanFail; then     mv output else     mv log     exit 1 #Exit with failure fi  exit 0 #Exit with success 

The rm tmp statement in the trap is always executed when the script exits, so the file "tmp" will always tried to be deleted.

Installed traps can also be reset; a call to trap with only a signal name will reset the signal handler.

trap EXIT 

For more details, see the bash manual page: man bash

like image 59
theycallhimart Avatar answered Sep 24 '22 22:09

theycallhimart