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
sleep ${poll_time}

//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?

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

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.

| improve this answer | |
  • I'm using buysbox and I guess inotifywait is not supported on that ? – richie Oct 28 '15 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. – Andrew Kozlov Oct 28 '15 at 20:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.