Bash – Killing background process in bash script when exiting the script

bashkillshell-scripttrap:

I have a script that tail a file while displaying a clock in the top right corner. I took the clock part from the internet, and it works ok. The entire script is something like (I simplified):

while sleep 1; do tput sc; tput cup 0 $(($(tput cols)-29)); date; tput rc; done &
tail -f mylog.log

All works well, but the problem is that when I stop the script using CTRL+C the clock continues to run in my console (until I manually kill the left-over bash process). So, is there a way to stop that process when I quit the script?

I tried the code below, but it does not work:

while sleep 1; do tput sc; tput cup 0 $(($(tput cols)-29)); date; tput rc; done &
CLOCK_PID=$!
tail -f mylog.log
kill -9 $CLOCK_PID

I searched how to trap CTRL+C in bash, but I'm not sure it's the right way…

Best Answer

CLOCK_PID=$!
trap 'kill -9 $CLOCK_PID' EXIT
tail -f mylog.log
Related Question