我有一个bash脚本,基本上是一个驱动程序。出于某种原因,Ubuntu无法自行分配蓝牙串口。该脚本的功能是连接蓝牙设备,然后在/ dev / bluetooth serial中为其分配一个位置。最后,当设备断开连接或按“q”终止时,它会终止端口。
我想知道在执行ctrl-C时是否有某种方法可以在bash脚本中执行命令,这样它就不会将不可用的设备留在我的/ dev文件夹中
答案 0 :(得分:9)
是的,你可以使用'trap'命令。按CTRL-C发送一个SIGINT,所以我们可以使用trap来捕获:
#!/bin/bash
trap "echo hello world" INT
sleep 10
如果在运行时按CTRL-C,它将执行命令(echo hello world
): - )
答案 1 :(得分:1)
$ 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 $$".
答案 2 :(得分:0)
使用陷阱。
trap "do_something" SIGINT
其中“do_something”是命令或函数名称。