2010-11-07 13 views
5

Tengo un script bash que básicamente sirve como controlador. Por alguna razón, Ubuntu no puede asignar el puerto serie Bluetooth por sí mismo. La función del guión es conectar un dispositivo bluetooth, luego asignarle un lugar para acceder en/dev/bluetooth serial. Finalmente, cuando el dispositivo se desconecta, o termina presionando "q", mata el puerto.BASH cómo ejecutar un comando en la terminación del script?

me gustaría saber si hay alguna manera de ejecutar un comando en un script bash cuando se ejecuta el Ctrl-C, de manera que no deje el dispositivo inutilizable en su lugar en mi carpeta/dev

Respuesta

8

Sí, puede usar el comando 'trap'. Pulsando CTRL-C envía un SIGINT, por lo que podemos utilizar trampa para la captura de que:

#!/bin/bash 

trap "echo hello world" INT 

sleep 10 

Si pulsa Ctrl-C cuando esta se ejecuta, que va a ejecutar el comando (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

Use una trampa.

trap "do_something" SIGINT 

donde "do_something" es un nombre de comando o función.

Cuestiones relacionadas