7
votes

BASH Comment exécuter une commande sur la terminaison de script?

J'ai un script Bash qui sert de conducteur fondamentalement. Pour une raison quelconque, Ubuntu ne peut pas attribuer le port série Bluetooth sur celui-ci. La fonction du script est de connecter un périphérique Bluetooth, puis d'attribuer une place à accéder à / dev / bluetooth. Enfin, lorsque l'appareil est déconnecté ou terminé en appuyant sur "Q", il tue le port.

J'aimerais savoir s'il y a un moyen d'exécuter une commande dans un script Bash lorsque le CTRL-C est exécuté de sorte qu'il ne laisse pas le périphérique inutilisable en place dans le dossier My / Dev


0 commentaires

3 Réponses :


2
votes
 $ 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 commentaires

0
votes

Utilisez un piège.

trap "do_something" SIGINT


0 commentaires

14
votes

Yep, vous pouvez utiliser la commande 'piège'. Frapper CTRL-C envoie un sigint, nous pouvons donc utiliser un piège pour attraper cela: xxx

si vous avez frappé Ctrl-C lorsque cela fonctionne, il exécutera la commande ( echo hello monde ): -)


1 commentaires

Peut être utilisé en boucle? Par exemple: faire quelque chose jusqu'à ce que CTRL + C soit enfoncé.