trap: trap [-lp] [[参数] 信号声明 ...]
    Trap signals and other events.

    Defines and activates handlers to be run when the shell receives signals
    or other conditions.

    ARG is a command to be read and executed when the shell receives the
    signal(s) SIGNAL_SPEC.  If ARG is absent (and a single SIGNAL_SPEC
    is supplied) or `-', each specified signal is reset to its original
    value.  If ARG is the null string each SIGNAL_SPEC is ignored by the
    shell and by the commands it invokes.

    If a SIGNAL_SPEC is EXIT (0) ARG is executed on exit from the shell.  If
    a SIGNAL_SPEC is DEBUG, ARG is executed before every simple command.  If
    a SIGNAL_SPEC is RETURN, ARG is executed each time a shell function or a
    script run by the . or source builtins finishes executing.  A SIGNAL_SPEC
    of ERR means to execute ARG each time a command's failure would cause the
    shell to exit when the -e option is enabled.

    If no arguments are supplied, trap prints the list of commands associated
    with each signal.

    Options:
      -l    print a list of signal names and their corresponding numbers
      -p    display the trap commands associated with each SIGNAL_SPEC

    Each SIGNAL_SPEC is either a signal name in <signal.h> or a signal number.
    Signal names are case insensitive and the SIG prefix is optional.  A
    signal may be sent to the shell with "kill -signal $$".

    Exit Status:
    Returns success unless a SIGSPEC is invalid or an invalid option is given.

trap是一个shell内建命令,它用来在脚本中指定信号如何处理。

比如,按Ctrl+C会使脚本终止执行,实际上系统发送了SIGINT信号给脚本进程,SIGINT信号的默认处理方式就是退出程序。

如果要在Ctrl+C不退出程序,那么就得使用trap命令来指定一下SIGINT的处理方式了。

trap命令不仅仅处理Linux信号,还能对脚本退出(EXIT)、调试(DEBUG)、错误(ERR)、返回(RETURN)等情况指定处理方式。

首先trap有两个选项:

-l 选项与 kill的-l选项一样的效果,就是打印所有的信号。

-p 后加信号 名字,默认不加是打印所有的。

然后改信号的应该是

trap "你要的操作" 信号

实例:

root@kali:~# trap "echo hello" INT
root@kali:~# trap -p INT
trap -- 'echo hello' SIGINT
root@kali:~# ^Chello  #按Ctrl+c键,可以看到hello别打印出来了

不用担心,退出终端在进入,即可恢复正常。

results matching ""

    No results matching ""