2010-11-07 21 views
5

Ho uno script bash che funge fondamentalmente da driver. Per qualche ragione Ubuntu non può assegnare la porta seriale Bluetooth su se stessa. La funzione dello script è quella di connettere un dispositivo bluetooth, quindi assegnargli un posto a cui accedere in/dev/bluetooth seriale. Infine, quando il dispositivo viene disconnesso o terminato premendo "q", uccide la porta.BASH come eseguire un comando sulla terminazione dello script?

Vorrei sapere se c'è qualche modo per eseguire un comando in uno script bash quando viene eseguito il ctrl-C in modo che non lascia il dispositivo inutilizzabile in atto nella mia cartella/dev

risposta

8

Sì, è possibile utilizzare il comando "trap". Premendo CTRL-C invia un SIGINT, in modo che possiamo utilizzare trappole per la cattura che:

#!/bin/bash 

trap "echo hello world" INT 

sleep 10 

Se si preme CTRL-C quando questo viene eseguito, sarà eseguire il 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

Utilizzare una trappola.

trap "do_something" SIGINT 

dove "do_qualcosa" è un nome di comando o funzione.

Problemi correlati