slick slick - 4 months ago 9x
Bash Question

How to cancel a process when Control+C is pressed in a shell script?

I have a script that does some work. It does it in a proper way but it takes a while before it ends. Because I want to simulate that "job is running now" I added a spinner cursor animation.

I call it at the beginning of my script, then I assign the PID of that function to a variable and when everything is done, I simply kill it to stop the animation.


spinner &

# a lot of stuff going on here...
# takes some time to finish

kill $SPINNER_PID &>/dev/null

printf "All done"

Function definition:

spinner() {
local i sp n
while sleep 0.1; do
printf "%s\b" "${sp:i++%n:1}"

All works fine if I won't interrupt.

Imagine that I want to cancel my long task by calling
. It cancels but the spinner obviously still animates since it's noting else that an infinite loop.

enter image description here

How I can kill it when script is cancelled manually and won't reach to
kill $SPINNER_PID &>/dev/null


There seems to be a statement called trap that allows you to run code when Ctrl-C is pressed. There is a good explanation of it here, and this website explains how to run a function on Ctrl-C.

trap your_func INT