tags:

views:

855

answers:

3

How can i, in a bash script, execute a command when the user stops the script (with ctrl - c)?

Currently, i have this:

afplay file.mp3

while true:
do osascript -e "set volume 10"
end

But i would like it to execute killall afplay when the user is finished with it, regardless if it is command-c or another keypress.

+7  A: 

trap 'killall afplay' EXIT

Vebjorn Ljosa
+3  A: 

Use trap.

trap "kill $pid" INT TERM EXIT

Also avoid killall or pkill, since it could kill unrelated processes (for instance, from another instance of your script, or even a different script). Instead, put the player's PID in a variable and kill only that PID.

CesarB
+2  A: 

You need to put a trap statement in your bash script:

trap 'killall afplay' EXIT

Note however that this won't work if the bash process is sent a KILL signal (9) as it's not possible for processes to intercept that signal.

Alnitak