BASH多个退出功能,用于不同的退出级别

时间:2016-12-06 09:44:35

标签: bash sh

如何在bash中使用多个退出陷阱? 说我想在退出代码1上运行on-exit-1 退出代码2上的on-exit-2

    function on-exit1 {
        echo "do stuff here if code had exit status 1"
        }
    function on-exit2 {
        echo "do stuff here if code had exit status 2"
        }
    .....

    trap on-exit1 EXIT # <--- what do i do here to specify the exit code to trap
    trap on-exit2 EXIT # <--- what do i do here to specify the exit code to trap
    .....
    some bashing up in here
    blah...blah
        exit 1 # do on-exit1
    else blah blah
        exit 2 # do on-exit2
    else blah blah
        exit N # do on-exitNth

2 个答案:

答案 0 :(得分:3)

以下代码示例应该可以工作:

exit_check () {
    # bash variable $? contains the last function exit code
    # will run the function on_exit1 if status exit is 1, on_exit2 if status exit is 2, ...
    on_exit$?
}
trap exit_check EXIT 

答案 1 :(得分:2)

如果你真的想使用陷阱,试试这个:

#!/usr/bin/env bash

function finish {
  echo "exitcode: $?"
}

trap finish EXIT

read -n 1 -s exitcode
exit $exitcode

但正如@ 123建议的那样,你可以打电话给你的退出功能,不需要滥用&#39;陷阱在这里。

尝试下次提供工作示例;)。