Bash script is not terminated with Ctrl+C

bashshell-scriptsignals

My script cannot be terminated with Ctrl+C key. It is an error.

Please explain how to modify my script to make it terminable by Ctrl+C.

#!/bin/bash

while true; do
  paplay /usr/share/sounds/phone.wav
done

Best Answer

If you catch SIGINT in the parent shell and exit the shell, it brings down paplay too:

trap exit SIGINT;
while true; do paplay  /usr/share/sounds/phone.wav ; done

It looks like paplay blocks the INT signal and that affects that prevents the parent shell from running its default handler.

Installing a handler in the parent shell in which you reset the handler and reraise the signal probably solves it in a better way:

trap 'trap - SIGINT; kill -SIGINT $$' SIGINT; 
while :; do paplay  /usr/share/sounds/linuxmint-login.wav ; done 

(With the exit approach the launcher process thinks its child exited voluntarily whereas with the second approach it looks like the script was killed with SIGINT which it was).

Related Question