Read/Search file being written to giving error due to timing issues

The following is a piece of code to rename LOG_FILE_NEW to LOG_FILE once you get a result (either RUNNING or SHUTDOWN)

RESULT=""
sleep 30
while [ "${RESULT}" = "" ]; do
sleep 10
RESULT=`sed -n '/RUNNING/'p ${LOG_FILE_NEW}`
if [ "${RESULT}" = "" ]; then
RESULT=`sed -n '/SHUTTING_DOWN/'p ${LOG_FILE_NEW}`
fi
done
mv ${LOG_FILE_NEW} ${LOG_FILE}

However, sometimes I get the following error.
sed: can't read x_new.log: No such file or directory
sed: can't read x_new.log: No such file or directory
sed: can't read x_new.log: No such file or directory

Seems to be a timing issue.

Anyone, any ideas?

It is always good practice to test for a file's existence prior to trying to move it.It would help if you stated what shell you are using and what the file variables are set to. If this is ksh then I think you should be using ==, I don't know any other shells. The most likely cause of the problem is the test for "" is failing as you are getting something unexpected back from the sed's. I would use grep -c myself and test for

-gt 0

It makes life a lot easier if you use code tags when posting this sort of thing.

Bourne shell

And LOG_FILE_NEW is set to /data/x_new.log
LOG_FILE to /data/x.log

This error doesnt happen always. It happens occasionally though either RUNNING or SHUTTING_DOWN do get written to the log.

I also tried to use lsof but it always returns 0. So it doesnt help.

RESULT=""
WRITE=0
sleep 30
while [ ${WRITE} = "0" ]; do
   sleep 10
   lsof ${LOG_FILE_NEW} > /dev/null 2>&1
   WRITE=$?
done
RESULT=`sed -n '/RUNNING/'p ${LOG_FILE_NEW}`
if [ "${RESULT}" = "" ]; then
   RESULT=`sed -n '/SHUTTING_DOWN/'p ${LOG_FILE_NEW}`
fi

mv ${LOG_FILE_NEW} ${LOG_FILE}

You are testing the sed output to see if it is an empty string but if the log file is not there RESULT =

sed: can't read x_new.log: No such file or directory

---------- Post updated at 05:33 PM ---------- Previous update was at 03:01 PM ----------

I think at a minimum you want to do something like this: -

${LOG_FILE_NEW}=x_new.log
${LOG_FILE}=some_log.log

[[ -a ${LOG_FILE_NEW} ]] && echo "Log file ${LOG_FILE_NEW} not found, exiting" && exit 1

while [[ true ]]
do
        [[ $(egrep -c "SHUTTING_DOWN|RUNNING" ${LOG_FILE_NEW}) -ne 0 ]] && break
        sleep 10
done
mv ${LOG_FILE_NEW} ${LOG_FILE}

Now you are not dependent on sed returning an empty string.