用途說明
trap是一個shell內建命令,它用來在腳本中指定信號如何處理。比如,按Ctrl+C會使腳本終止執行,實際上系統傳送了SIGINT信號給腳本進程,SIGINT信號的默認處理方式就是退出程式。如果要在Ctrl+C不退出程式,那么就得使用trap命令來指定一下SIGINT的處理方式了。trap命令不僅僅處理Linux信號,還能對腳本退出(EXIT)、調試(DEBUG)、錯誤(ERR)、返回(RETURN)等情況指定處理方式。
常用參數
通式
trap [-lp] [[arg] sigspec ...]
格式1
trap "commands" signals
當shell接收到signals指定的信號時,執行commands命令。(The command arg is to be read and executed when the shell receives signal(s) sigspec. )
格式2
trap signals
如果沒有指定命令部分,那么就將信號處理復原。比如 trap INT 就表明恢復Ctrl+C退出。(If arg is absent (and there is a single sigspec) or -, each specified signal is reset to its original disposition (the value it had upon entrance to the shell). )
格式3
trap "" signals
忽略信號signals,可以多個,比如 trap "" INT 表明忽略SIGINT信號,按Ctrl+C也不能使腳本退出。又如 trap "" HUP 表明忽略SIGHUP信號,即網路斷開時也不能使腳本退出。(If arg is the null string the signal specified by each sigspec is ignored by the shell and by the commands it invokes. )
格式4
trap -p
格式:trap -p signal
把當前的trap設定列印出來。(If arg is not present and -p has been supplied, then the trap commands associated with each sigspec are displayed. If no arguments are supplied or if only -p is given, trap prints the list of commands associated with each signal.)
格式5
trap -l
把所有信號列印出來。(The -l option causes the shell to print a list of signal names and their corresponding numbers. Each sigspec is either a signal name defined in <signal.h>, or a signal number. Signal names are case insensitive and the SIG prefix is optional.)
格式6
trap "commands" EXIT
腳本退出時執行commands指定的命令。(If a sigspec is EXIT (0) the command arg is executed on exit from the shell.)
格式7
trap "commands" DEBUG
在腳本執行時列印調試信息,比如列印將要執行的命令及參數列表。(If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function (see SHELL GRAMMAR above). Refer to the description of the extdebug option to the shopt builtin for details of its effect on the DEBUG trap.)
格式8
trap "commands" ERR
當命令出錯,退出碼非0,執行commands指定的命令。(If a sigspec is ERR, the command arg is executed whenever a simple command has a non-zero exit status, subject to the following conditions. The ERR trap is not executed if the failed command is part of the command list immediately following a while or until keyword, part of the test in an if statement, part of a && or ┅Ι│ list, or if the command’s return value is being inverted via !. These are the same conditions obeyed by the errexit option.)
格式9
trap "commands" RETURN
當從shell函式返回、或者使用source命令執行另一個腳本檔案時,執行commands指定的命令。(If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing. Signals ignored upon entry to the shell cannot be trapped or reset. Trapped signals that are not being ignored are reset to their original values in a child process when it is created. The return status is false if any sigspec is invalid; otherwise trap returns true.)