How can i, in a bash script, execute a command when the user stops the script (with ctrl - c)?
我怎样才能在bash脚本中执行命令,当用户停止脚本时(使用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.
但是我想在用户完成它时执行killall afplay,无论它是command-c还是其他按键。
3 个解决方案
#1
9
trap 'killall afplay' EXIT
陷阱'killall afplay'EXIT
#2
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.
还要避免使用killall或pkill,因为它可以杀死不相关的进程(例如,来自脚本的另一个实例,甚至是不同的脚本)。相反,将玩家的PID放在变量中并仅杀死该PID。
#3
2
You need to put a trap
statement in your bash script:
您需要在bash脚本中放置一个trap语句:
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.
但是请注意,如果bash进程发送了KILL信号(9),这将不起作用,因为进程无法拦截该信号。
#1
9
trap 'killall afplay' EXIT
陷阱'killall afplay'EXIT
#2
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.
还要避免使用killall或pkill,因为它可以杀死不相关的进程(例如,来自脚本的另一个实例,甚至是不同的脚本)。相反,将玩家的PID放在变量中并仅杀死该PID。
#3
2
You need to put a trap
statement in your bash script:
您需要在bash脚本中放置一个trap语句:
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.
但是请注意,如果bash进程发送了KILL信号(9),这将不起作用,因为进程无法拦截该信号。