1

I'm trying to write a script that traps a exit signal and terminate. Instead of using the usual bash trap method, I would like to monitor a file creation every 10 seconds and cleanup some stuff before termination.

Here is what I have tried:

poll_time=10 // poll every 10 seconds
((term_time=$SECONDS+240)) // monitor until 4 min from current script time exec

while (( $SECONDS < $term_time)) do
    if [[ -r $some_path/file.txt ]]; then
        cleanup_function
        exit
fi
sleep ${poll_time}
done

//if file doesnt exit continue with below code
//blah blah blah ....

Is there a better way to do this? will above lines of code work?

1
  • It won't work because of your syntax errors. Add a semicolon or a newline before your do, and use # blah for comments. Oct 28, 2015 at 18:46

1 Answer 1

5

inotifywait from inotify-tools is what you need (to look at at least). Line like this will do the same trick your script is intended to do:

inotifywait -e create --timeout 240 "${some_path}/file.txt" && { cleanup_function; exit ; }

with the difference inotifywait works in event-based manner, so no polling or sleeping required.

2
  • I'm using buysbox and I guess inotifywait is not supported on that ?
    – richie
    Oct 28, 2015 at 18:59
  • 1
    @richie BusyBox has builtin tool inotifyd serving the same purposes. Though it has limited functionality compared to inotify-tools, e.g. no timeout option or need to have separate script to handle event. Alternatively, you can try and install inotify-tools manually. Oct 28, 2015 at 20:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .