Conditional execution

Here's an interesting (to me, anyway) little puzzle.

Background:
I have a process that restores a number of large(ish) files from tape backup. As an individual file is being written, it is owned by root, then the ownership is changed when that file is complete. Since this process can take some time (and operations, who actually runs it) isn't timely about starting it when requested or telling me when it completes, I wrote a little script to watch for the presence of the root-owned files:

echo "Please enter sleep interval: "
read sleep_interval
while :
do
ls -ltr /mydir |grep root
date
echo Sleeping $sleep_interval seconds
sleep $sleep_interval
done

So when I first kick it off, I set the sleep interval to something large, like 300. Then when I see files who are owned by root showing up, I cancel the script and resubmit with a sleep interval of 10.

So it occurs to me, could I code it to self-determine what the sleep interval should be. Check the outcome of the 'ls', and if nothing is owned by root sleep for 300, else sleep for 10. So, on first starting, there would be no files, so it would sleep for 300. On the first iteration that turns up a file, sleep goes to 10, and on first following iteration with no files owned by root, sleep goes back to 300.

In pseudo code, something like this:

while :
do
ls -ltr /mydir |grep root|grep -v "lost+found"
#- begin pseudo code
if nothing found
   sleep 300
else
   sleep 10
fi
# - end pseudo code
done

I'd use a variable for that. When you detect files, change the variable, and it'll stay changed.

find may be more efficient than ls | grep.

trap "rm -f /tmp/$$" EXIT
INTERVAL=300

while true
do
        find /mydir -uname root '!' -path 'lost+found' > /tmp/$$
        # If the file is not empty, set the interval to 10
        [ -s /tmp/$$ ] || INTERVAL=10
        cat /tmp/$$
        sleep $INTERVAL
done
1 Like

Thanks. That was essentially what I needed. A little tweaking gave it the needed ability to switch back and forth ..

( for testing I shortened the intervals)

trap "rm -f /tmp/$$" EXIT
INTERVAL=10
while true
do
  find /home/oracle -user root '!' -path 'lost+found' > /tmp/$$
  # if the file is not empty, set the interval to 10
  if [ -s /tmp/$$ ]
  then
  INTERVAL=5
  else
  INTERVAL=10
  fi
  cat /tmp/$$
  ls -l /tmp/$$
  date
  echo Sleeping $INTERVAL
  sleep $INTERVAL
done
1 Like

You can shorten that a bit:

INTERVAL=30
[ -s /tmp/$$ ] && INTERVAL=5