I need to create a shell script that executes an application when a file called start is created in a particular directory.

How may I write a shell script that waits for the creation of a file with a certain name in a certain location?

  • I don't think the question is actually about how to create a file called start but how to trigger a script when a file appears with a certain name. Am I right? – Kusalananda Sep 13 '17 at 13:00
  • Yes @Kusalananda, correct!! – kumar shivam Sep 13 '17 at 13:03
  • @kumarshivam I reworded the question. Hopefully you will be ok with the new wording. – Kusalananda Sep 13 '17 at 13:09
  • 5
    Wouldn't inotify be a good candidate for this. – Raman Sailopal Sep 13 '17 at 13:18
  • 2
    We should clarify the operating environment here -- @kumar, what OS does this need to run on? – Jeff Schaller Sep 13 '17 at 13:23

If your system has inotifywait (most Linux distributions, OpenBSD and possibly others), as others have mentioned the least resource-intensive approach is to use inotifywait:

rm -f yourdirectory/start
while [ "$(inotifywait -e create -q --format %f yourdirectory)" != "start" ]; do :; done

That will ensure the start file is removed from yourdirectory, then wait for its creation, and then run yourcommand. -e create specifies that we’re only interested in creation events, -q specifies that we don’t want inotifywait’s diagnostic messages, and --format %f specifies that we only want to see the created file’s name in the output.

If you don’t have inotifywait, the following will work too, with a delay of at most one second:

rm -f yourdirectory/start
while [ ! -e yourdirectory/start ]; do sleep 1; done

I like the tool 'inoticoming' for watching a directory for change. has logging and pid-file creation. you can run command on change with additional 'action-options' it's pretty decent :)

i also remember a tool called 'fileschanged' but never got to play with it, could be worth a look. -Jay

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.