I have a bash script like this:
#!/bin/bash
startsomeservice &
echo $! > service.pid
while true; do
# dosomething in repeat all the time here
foo bar
sleep 5
done
# cleanup stuff on abort here
rm tmpfiles
kill $(cat service.pid)
the problem of this script is, that i cant abort it. If i press ctrl+c i just go into the next loop... Is it possible to run a script like this but to have it abortable?
Since you are executing the script with Bash, you can do the following:
#!/bin/bash
startsomeservice &
echo $! > service.pid
finish()
{
rm tmpfiles
kill $(cat service.pid)
exit
}
trap finish SIGINT
while :; do
foo bar
sleep 5
done
Please note that this behaviour is Bash specific, if you run it with Dash, for instance, you will see two differences:
SIGINT
Note also that you will break a shell loop with a single C-c
when you execute the loop directly from an interactive prompt, even if you're running Bash. See this detailed discussion about SIGINT
handling from shells.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With