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 }
There is no try/catch in bash; however, one can achieve similar behavior using && or || . it stops your script if any simple command fails.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With