2010-11-07 71 views
5

我有一个基本上作为驱动程序的bash脚本。由于某些原因,Ubuntu无法自行分配蓝牙串行端口。该脚本的功能是连接蓝牙设备,然后为其分配一个要访问的位置/ dev/bluetooth serial。最后,当设备断开连接时,或者按下“q”终止设备时,它会终止端口。BASH如何执行脚本终止命令?

我想知道是否有某种方式执行CTRL-C时,在bash脚本来执行命令,使其不留在原地无法使用的设备在我的/ dev目录

回答

8

是的,你可以使用'陷阱'命令。按CTRL-C发送SIGINT,所以我们可以使用陷阱赶上那:

#!/bin/bash 

trap "echo hello world" INT 

sleep 10 

如果按CTRL-C时,这个运行时,它会:-)

执行命令( echo hello world
0
$ 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 $$". 
0

使用陷阱。

trap "do_something" SIGINT 

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