11

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

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."
}
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.

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.