I am trying to use find within an if statement.
Problem is, even though my find returns nothing, the RC is 0 and continues.
Intent - check the log of a weekly job for successful completion. If complete, carry on. If not, tell me and exit. Suggestions?
I have tried the following:
if find /var/opt/logdir/* -mtime -7 -exec grep "completes" {} \;
then
crontab -l > /tmp/root_cron.$DATE
crontab -l | sed '/\/usr\/local\/bin\/job/s!^!#!' > /tmp/root_cron.new
crontab /tmp/root_cron.new
else
echo "copy job did not complete"
exit 0
fi
Results from command line:
$ find /var/opt/logdir/* -mtime -7 -exec grep "completes" {} \;
$ echo $?
$ 0
$ find /var/opt/logdir/* -mtime -7
$ echo $?
$ 0
$ find /var/opt/logdir/*
/var/opt/logdir/job.log.Mon
/var/opt/logdir/job.log.Tue
/var/opt/logdir/job.log.Wed
Try...
if grep completes `find /var/opt/logdir/ -mtime -7 `
then
crontab -l > /tmp/root_cron.$DATE
crontab -l | sed '/\/usr\/local\/bin\/job/s!^!#!' > /tmp/root_cron.new
crontab /tmp/root_cron.new
else
echo "copy job did not complete"
exit 0
fi
This gets a whole list of files and then greps in one go rather than file by file as the original did.
JerryHone, thanks for the response. This works great if the find returns a file. However, in the event the job has not run in the last 7 days, there is no file returned and we are left with
grep completes <blank>
which just sits there. Any other thoughts?
I came up with an alternate solution. redirect the find output to a new file then test the new file. if empty, bail out, else grep for complete from the file found.
if grep completes /dev/null `find /var/opt/logdir/ -mtime -7 `
then
crontab -l > /tmp/root_cron.$DATE
crontab -l | sed '/\/usr\/local\/bin\/job/s!^!#!' > /tmp/root_cron.new
crontab /tmp/root_cron.new
else
echo "copy job did not complete"
exit 0
fi
This will always grep through /dev/null. That will always result in a false so the results of the find should drive the 'if' clause
here is a alternetive
AMIT=`find /var/opt/logdir/* -mtime -7 -exec grep "completes" {} \`
if [ $AMIT -ge 1 ]
then
print "${@} Ok"
else
print "${@} Not Ok"
RETURN_CODE=106
exit $RETURN_CODE
fi
Old versions of find would return an error if nothing was found, but newer ones don't. Instead, check whether anything was found with:
found=$( find /var/opt/logdir/* -mtime -7 -exec grep "completes" {} \; )
if [ -n "$found" ]
then
crontab -l > /tmp/root_cron.$DATE
crontab -l | sed '/\/usr\/local\/bin\/job/s!^!#!' > /tmp/root_cron.new
crontab /tmp/root_cron.new
else
echo "copy job did not complete"
exit 0
fi