40

I need a script that will wait for a (examplefile.txt) to appear in the /tmp directory

and once it's found to stop the program, otherwise to sleep the file until it's located

So far I have:

if [ ! -f /tmp/examplefile.txt ]

then

Ahmed Ashour
  • 2,490
Cidricc
  • 543

2 Answers2

62
until [ -f /tmp/examplefile.txt ]
do
     sleep 5
done
echo "File found"
exit

Info: Use -d instead of -f to check for directories, or -e to check for files or directories.

Every 5 seconds it will wake up and look for the file. When the file appears, it will drop out of the loop, tell you it found the file and exit (not required, but tidy.)

Put that into a script and start it as script &

That will run it in the background.

There may be subtle differences in syntax depending on the shell you use. But that is the gist of it.

Jeff Dodd
  • 741
31

Try this shell function:

# Block until the given file appears or the given timeout is reached.
# Exit status is 0 iff the file exists.
wait_file() {
  local file="$1"; shift
  local wait_seconds="${1:-10}"; shift # 10 seconds as default timeout
  test $wait_seconds -lt 1 && echo 'At least 1 second is required' && return 1

until test $((wait_seconds--)) -eq 0 -o -e "$file" ; do sleep 1; done

test $wait_seconds -ge 0 # equivalent: let ++wait_seconds }

And here's how you can use it:

# Wait at most 5 seconds for the server.log file to appear

server_log=/var/log/jboss/server.log

wait_file "$server_log" 5 || { echo "JBoss log file missing after waiting for 5 seconds: '$server_log'" exit 1 }

Another example:

# Use the default timeout of 10 seconds:
wait_file "/tmp/examplefile.txt" && {
  echo "File found."
}
Elifarley
  • 678