Linux shell try catch finally

2019-03-08 09:49发布

问题:

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
}

回答1:

Well, sort of:

{ # your 'try' block
    executeCommandWhichCanFail &&
    mv output
} || { # your 'catch' block
    mv log
}

 rm tmp # finally: this will always happen


回答2:

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



回答3:

mv takes two parameters, so may be you really wanted to cat the output file's contents:

echo `{ execCommand && cat output ; } || cat log`
rm -f tmp