23
Apr

Shell Script While Loop to Wait for a File to Appear or Else Timeout

The following shell script snippit will continually check and wait for the presence of a file until it is found, or until it reaches a timeout period, which in this case, is about 10 seconds, whichever come first.

#/bin/sh

x=0
while [ "$x" -lt 100 -a ! -e /path/to/the/file_name ]; do
        x=$((x+1))
        sleep .1
done

This can be helpful to prevent a race condition in a script if you’re say, mounting a filesystem from an external device. You could take it a step further and print useful messages as well:

#/bin/sh
$FILE="/path/to/the/file_name"
x=0
while [ "$x" -lt 100 -a ! -e $FILE ]; do
   x=$((x+1))
   sleep .1
done
if [ -e $FILE ]
then
   echo "Found: $FILE"
else
   echo "File $FILE not found within time limit!"
fi

Another, maybe more elegant, solution is to use the wait command:

wait [pid]...

Wait for your background process whose process ID is pid and report its termination status. If pid is omitted, all your shell’s currently active background processes are waited for and the return code will be 0. The wait utility accepts a job identifier, when Job Control is enabled (jsh), and the argument, jobid, is preceded by a percent sign (%).

If pid is not an active process ID, the wait utility will return immediately and the return code will be 0.

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 0 Comment So Far

Share your thoughts, leave a comment!