Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run command when bash script is stopped

Tags:

bash

macos

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.

like image 972
Josh Hunt Avatar asked Oct 30 '08 09:10

Josh Hunt


People also ask

What is bash trap command?

A built-in bash command that is used to execute a command when the shell receives any signal is called `trap`. When any event occurs then bash sends the notification by any signal. Many signals are available in bash. The most common signal of bash is SIGINT (Signal Interrupt).

Does a Bash script wait for command to finish?

The bash wait command is a Shell command that waits for background running processes to complete and returns the exit status. Unlike the sleep command, which waits for a specified time, the wait command waits for all or specific background tasks to finish.

What is the Run command for bash?

In order to run a Bash script on your system, you have to use the “bash” command and specify the script name that you want to execute, with optional arguments. Alternatively, you can use “sh” if your distribution has the sh utility installed.

Does bash have a Continue statement?

The Bash continue statement resumes the following iteration in a loop or looping statement. The continue statement only has meaning when applied to loops. The integer value indicates the depth for the continue statement. By default, the integer is 1 and writing the number is not mandatory.


1 Answers

trap 'killall afplay' EXIT

like image 90
Vebjorn Ljosa Avatar answered Oct 18 '22 20:10

Vebjorn Ljosa