Bash:两次发出陷阱

Mat*_*hid 9 shell bash trap

如果我trap两次发出内置命令 [对于相同的信号],会发生什么?第二个命令是添加到第一个命令中,还是替换第一个命令?

trap Foo SIGINT
...
trap Bar SIGINT
...
Run Code Online (Sandbox Code Playgroud)

当 SIGINT 发生时,Bash 是直接运行Bar还是同时运行Foo?或者是其他东西...?

wur*_*tel 8

命令被替换。

联机帮助页指出:

 trap [-lp] [[arg] sigspec ...]
        The  command  arg  is  to  be  read  and executed when the shell
        receives signal(s) sigspec.  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).   If arg is the null string the signal specified by each
        sigspec is ignored by the shell and by the commands it  invokes.
        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.   The  -l  option
        causes  the shell to print a list of signal names and their cor?
        responding 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.
Run Code Online (Sandbox Code Playgroud)

它陈述the command arg is to be read and executed ...时期。如果始终将 arg 添加到列表中,则无法重置信号处理。

  • 这同样适用于例如设置别名...是否将别名设置两次*添加*到现有别名,或替换它?(当然它取代了它。)你只是阅读了太多内容,只是期望 bash 做简单的事情:-) (3认同)
  • 我读了那个确切的段落,但我并不清楚“将读取和执行命令 arg”意味着删除任何先前的命令。然而,情况似乎确实如此。 (2认同)

Gil*_*il' 7

手册

trap [-lp] [arg] [sigspec …]

当 shell 接收到信号sigspec时,将读取和执行arg中的命令。

该描述没有说明添加到现有命令列表中的任何内容。当arg为空或 string时,它继续指定非增量效果-。虽然文本可能没有明确说明命令没有添加到列表中,但它从未提及任何此类列表,或从所述列表中删除项目的任何方法。因此,以暗示将连续trap命令添加arg到列表的方式来解释此文本是相当牵强的。

您可以通过查看另一个 shell 的手册来确定。如果 bash 偏离通常的行为,手册会明确说明。该POSIX标准对此事毫不含糊:

陷阱的动作应覆盖先前的动作(默认动作或明确设置的动作)。