Unix Script: Wait until a file exists

11

2

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

Cidricc

Posted 2015-02-16T16:21:58.377

Reputation: 143

Answers

16

This bash function will block until the given file appears or a given timeout is reached. The exit status will be 0 if the file exists; if it doesn't, the exit status will reflect how many seconds the function has waited.

wait_file() {
  local file="$1"; shift
  local wait_seconds="${1:-10}"; shift # 10 seconds as default timeout

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

  ((++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 $? seconds: '$server_log'"
  exit 1
}

Another example:

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

Elifarley

Posted 2015-02-16T16:21:58.377

Reputation: 428

10

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

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

Posted 2015-02-16T16:21:58.377

Reputation: 121