开发者

BASH how to execute a command on script termination?

I have a bash script which serves as a driver basically. For some reason Ubuntu cannot assign the Bluetooth Serial port on it's own. The script's function is to connect up a bluetooth device, then assign it a place to be accessed in /dev/bluetooth serial. Finally, when the device is disconnected, or terminated by pressing "q", it kills the port.

I would like to know if there is some way to execute a command in a bash script when the ctrl-C is executed so that it does not leave the unusable device in 开发者_如何学Cplace in my /dev folder


Yep, you can use the 'trap' command. Hitting CTRL-C sends a SIGINT, so we can use trap to catch that:

#!/bin/bash

trap "echo hello world" INT

sleep 10

If you hit CTRL-C when this runs, it'll execute the command (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 $$".


Use a trap.

trap "do_something" SIGINT

where "do_something" is a command or function name.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜