【发布时间】:2010-11-07 14:33:51
【问题描述】:
我有一个基本上用作驱动程序的 bash 脚本。由于某种原因,Ubuntu 无法自行分配蓝牙串行端口。该脚本的功能是连接蓝牙设备,然后在 /dev/bluetooth 串行中为其分配一个可以访问的位置。最后,当设备断开连接或按“q”终止时,它会终止端口。
我想知道在执行 ctrl-C 时是否有某种方法可以在 bash 脚本中执行命令,这样它就不会将不可用的设备留在我的 /dev 文件夹中
【问题讨论】:
我有一个基本上用作驱动程序的 bash 脚本。由于某种原因,Ubuntu 无法自行分配蓝牙串行端口。该脚本的功能是连接蓝牙设备,然后在 /dev/bluetooth 串行中为其分配一个可以访问的位置。最后,当设备断开连接或按“q”终止时,它会终止端口。
我想知道在执行 ctrl-C 时是否有某种方法可以在 bash 脚本中执行命令,这样它就不会将不可用的设备留在我的 /dev 文件夹中
【问题讨论】:
是的,您可以使用“trap”命令。按下 CTRL-C 会发送一个 SIGINT,所以我们可以使用陷阱来捕捉它:
#!/bin/bash
trap "echo hello world" INT
sleep 10
如果您在运行时按 CTRL-C,它将执行命令 (echo hello world) :-)
【讨论】:
$ 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 $$".
【讨论】:
使用陷阱。
trap "do_something" SIGINT
其中“do_something”是命令或函数名称。
【讨论】: