Linux shell try catch finally

2019-03-08 10:09发布

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
}

3条回答
看我几分像从前
2楼-- · 2019-03-08 10:10

Well, sort of:

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

 rm tmp # finally: this will always happen
查看更多
不美不萌又怎样
3楼-- · 2019-03-08 10:20

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

查看更多
你好瞎i
4楼-- · 2019-03-08 10:26

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
查看更多
登录 后发表回答