Reputation: 326
I want to keep polling file till it arrives at the location for 1 hour.
My dir : /home/stage
File Name (which I am looking for): abc.txt
I want to keep polling directory /home/stage
for 1 hour but within the 1 hour if abc.txt
file arrives then it should stop polling and should display the message file arrived
otherwise after 1 hour it should display that file has not arrived
.
Is there any way to achieve this in Unix?
Upvotes: 6
Views: 16824
Reputation: 109
Here some answer with retry:
cur_poll_c=0
echo "current poll count= $cur_poll_c"
while (($cur_poll_c < $maxpol_count)) && (($SECONDS < $end_time))
do
if [[ -f $s_dir/$input_file ]]
then
echo "File has arrived...
do some operation...
sleep 5
exit 0
fi
sleep $interval
echo "Retring for $cur_poll_c time .."
cur_poll_c=`expr $cur_poll_c+1`;
done
Upvotes: 0
Reputation: 123498
The following script should work for you. It would poll for the file every minute for an hour.
#!/bin/bash
duration=3600
interval=60
pid=$$
file="/home/stage/abc.txt"
( sleep ${duration}; { ps -p $pid 1>/dev/null && kill -HUP $pid; } ) &
trap "echo \"file has not arrived\"; kill $pid" SIGHUP
while true;
do
[ -f ${file} ] && { echo "file arrived"; exit; }
sleep ${interval}
done
Upvotes: 4
Reputation: 62379
Another bash
method, not relying on trap handlers and signals, in case your larger scope already uses them for other things:
#!/bin/bash
interval=60
((end_time=${SECONDS}+3600))
directory=${HOME}
file=abc.txt
while ((${SECONDS} < ${end_time}))
do
if [[ -r ${directory}/${file} ]]
then
echo "File has arrived."
exit 0
fi
sleep ${interval}
done
echo "File did not arrive."
exit 1
Upvotes: 16
Reputation: 879
Here's an inotify script to check for abc.txt
:
#!/bin/sh
timeout 1h \
inotifywait \
--quiet \
--event create \
--format '%f' \
--monitor /home/stage |
while read FILE; do \
[ "$FILE" = 'abc.txt' ] && echo "File $FILE arrived." && kill $$
done
exit 0
The timeout
command quits the process after one hour. In case the file arrives, the process kills itself.
Upvotes: 3
Reputation: 72755
You can use inotify to monitor the directory for modifications and then check to see if the file is abc.txt. The inotifywait(1) command lets you do this directly from the command line in a shell script. Check the man page for details. This is notification based.
A poll based thing would be a loop that checks to see if the file exists and if not, sleep for a period of time before checking again. That's a trivial shell script too.
Upvotes: 1