Writing try catch finally in shell

﹥>﹥吖頭↗ 提交于 2019-12-03 01:35:28

问题


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


来源:https://stackoverflow.com/questions/15656492/writing-try-catch-finally-in-shell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!