Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Let bash script run all the time but be abortable

Tags:

bash

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?

like image 556
reox Avatar asked Jun 12 '12 09:06

reox


1 Answers

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:

  1. You cannot capture SIGINT
  2. The interrupt signal will break the shell loop.

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.

like image 162
C2H5OH Avatar answered Sep 29 '22 05:09

C2H5OH