我有一个bash脚本,基本上充当驱动程序。由于某些原因,Ubuntu不能自行分配蓝牙串口。该脚本的功能是连接蓝牙设备,然后将其分配到/dev/bluetooth串口中以便访问。最后,当设备断开连接或通过按“q”终止时,它会关闭端口。
我想知道是否有一种方法在执行ctrl-C时在bash脚本中执行命令,以便不会在我的/dev文件夹中留下无法使用的设备。
我想知道是否有一种方法在执行ctrl-C时在bash脚本中执行命令,以便不会在我的/dev文件夹中留下无法使用的设备。
没错,你可以使用'trap'命令。按下CTRL-C会发送SIGINT信号,因此我们可以使用trap来捕获它:
#!/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”是一个命令或函数名称。