Matt Komarnicki
Matt Komarnicki

Reputation: 5422

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.

#!/bin/bash

spinner &
SPINNER_PID=$!

# 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
  sp='/-\|'
  n=${#sp}
  while sleep 0.1; do
    printf "%s\b" "${sp:i++%n:1}"
  done
}

All works fine if I won't interrupt.

Imagine that I want to cancel my long task by calling Control+C. 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?

Upvotes: 1

Views: 798

Answers (1)

jfdoming
jfdoming

Reputation: 975

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

Upvotes: 3

Related Questions