2016-12-06 66 views
1

如何在bash中使用多個退出陷阱? 說我想在退出-1上的退出代碼1 和退出-2退出代碼2BASH不同退出級別的多個退出函數

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 
+4

你爲什麼要捕捉退出,在功能只是出口,並呼籲他們不是退出的? – 123

+1

或者像@ 123所提到的那樣做,或者定義一個退出函數並檢查退出代碼的'$?'。 – infotoni91

+1

'exit_check EXIT'和'exit_check(){status =「$?」; [「$ status」-eq 1] && on_exit1 && return 0; [「$ status」-eq 2] && on_exit2 && return 0; }' – Aserre

回答

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 
2

如果你真的想用陷阱運行,試試這個:

#!/usr/bin/env bash 

function finish { 
    echo "exitcode: $?" 
} 

trap finish EXIT 

read -n 1 -s exitcode 
exit $exitcode 

但是,如@ 123所示,您可以調用您的退出函數,無需在此處「濫用」陷阱。

下次嘗試提供工作示例;)。