I’m looking for a way to run a script for x seconds with still the possibility to interrupt it before those x seconds are past.
If I didn’t need the ability to Ctrl-C I’d write
./my_script &
sleep $x
kill $!
But here if I Ctrl-C during the script the fork keeps running.
I kinda know how to kill the script if launched in a sub-shell:
trap "echo sub-script terminated" INT
(./my_script)
trap - INT
but I do not know how to transpose that to a fork (I do not get clearly the differences between the two concepts I have to admit).
EDIT: I’d like to know how portable are the solutions btw, if you can mention that in your answers, that’d be of great value to me.
If you have a reasonably new GNU Coreutils,
timeoutis included there. Before, there used to be a number of slightly incompatibletimeoutvariants from different sources (the one I have in most places comes from the Postfix distribution originally IIRC).If you don’t have
timeoutfor your distro, there are many shell and Perl hacks out there.