How do I wait for a file in the shell script? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How do I wait for a file in the shell script? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to write a shell script that will wait for a file to appear in the /tmp directory called sleep.txt and once it is found the program will cease, otherwise I want the program to be in a sleep (suspended) state until the file is located. Now, I’m assuming that I will use a test command. So, something like

(if [ -f "/tmp/sleep.txt" ]; 
then stop 
   else sleep.)

I’m brand new to writing shell script and any help is greatly appreciated!


Under Linux, you can use the inotify kernel subsystem to efficiently wait for the appearance of a file in a directory:

while read i; do if [ "$i" = sleep.txt ]; then break; fi; done 
   < <(inotifywait  -e create,open --format '%f' --quiet /tmp --monitor)
# script execution continues ...

(assuming Bash for the <() output redirection syntax)

The advantage of this approach in comparison to fixed time interval polling like in

while [ ! -f /tmp/sleep.txt ]; do sleep 1; done
# script execution continues ...

is that the kernel sleeps more. With an inotify event specification like create,open the script is just scheduled for execution when a file under /tmp is created or opened. With the fixed time interval polling you waste CPU cycles for each time increment.

I included the open event to also register touch /tmp/sleep.txt when the file already exists.

We are here to answer your question about How do I wait for a file in the shell script? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji