代码之家  ›  专栏  ›  技术社区  ›  Adam Outler

BASH如何在脚本终止时执行命令?

  •  6
  • Adam Outler  · 技术社区  · 14 年前

    我想知道在执行ctrl-C时是否有方法在bash脚本中执行命令,这样就不会在/dev文件夹中留下不可用的设备

    3 回复  |  直到 14 年前
        1
  •  10
  •   Callie J    14 年前

    是的,你可以使用“trap”命令。点击CTRL-C会发送一个SIGINT,因此我们可以使用trap来捕捉:

    #!/bin/bash
    
    trap "echo hello world" INT
    
    sleep 10
    

    如果在运行时按CTRL-C,它将执行命令( echo hello world

        2
  •  2
  •   Logan Capaldo    14 年前
     $ help trap
    
     trap: trap [-lp] [arg signal_spec ...]
         The command ARG is to be read and executed when the shell receives
         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)
         the command ARG is executed on exit from the shell.  If a SIGNAL_SPEC
         is DEBUG, ARG is executed after every simple command.  If the`-p' option
         is supplied then the trap commands associated with each SIGNAL_SPEC are
         displayed.  If no arguments are supplied or if only `-p' is given, trap
         prints the list of commands associated with each signal.  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.  `trap -l' prints
         a list of signal names and their corresponding numbers.  Note that a
         signal can be sent to the shell with "kill -signal $$".
    
        3
  •  0
  •   Dennis Williamson    14 年前

    使用陷阱。

    trap "do_something" SIGINT
    

    其中“do_something”是命令或函数名。