Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 place in my /dev folder

like image 296
Adam Outler Avatar asked Nov 07 '10 14:11

Adam Outler


People also ask

How do you end a command in a script?

To close an interactive command prompt, the keyboard shortcut ALT + F4 is an alternative to typing EXIT.

How do you terminate a shell script if statement?

To end a shell script and set its exit status, use the exit command. Give exit the exit status that your script should have. If it has no explicit status, it will exit with the status of the last command run.

What does \r do in bash?

The -r tests if the file exists and if you have read permission on the file. Bash scripting tutorial - if statement. The meaning of -r depends on what program/command it is given as an argument for. In this case it is for [ , and means to check whether the file named by the next argument is readable.


1 Answers

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) :-)

like image 180
Chris J Avatar answered Oct 19 '22 09:10

Chris J