【问题标题】:BASH how to execute a command on script termination?BASH如何在脚本终止时执行命令?
【发布时间】:2010-11-07 14:33:51
【问题描述】:

我有一个基本上用作驱动程序的 bash 脚本。由于某种原因,Ubuntu 无法自行分配蓝牙串行端口。该脚本的功能是连接蓝牙设备,然后在 /dev/bluetooth 串行中为其分配一个可以访问的位置。最后,当设备断开连接或按“q”终止时,它会终止端口。

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

【问题讨论】:

    标签: bash driver device


    【解决方案1】:

    是的,您可以使用“trap”命令。按下 CTRL-C 会发送一个 SIGINT,所以我们可以使用陷阱来捕捉它:

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

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

    【讨论】:

    • 可以循环使用吗?例如:做某事直到按下 Ctrl+c。
    【解决方案2】:
     $ 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】:

      使用陷阱。

      trap "do_something" SIGINT
      

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

      【讨论】:

        猜你喜欢
        • 2012-10-24
        • 2022-10-25
        • 2022-10-14
        • 2015-04-24
        • 1970-01-01
        • 2021-02-12
        • 2020-12-08
        • 2010-09-19
        • 1970-01-01
        相关资源
        最近更新 更多