6

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.

3 Answers 3

10

trap 'killall afplay' EXIT

Sign up to request clarification or add additional context in comments.

Comments

4

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.

1 Comment

Do you have any suggestions for grabbing the pid of a process? (I imagine it being straight forward if the process is started locally)
2

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.