Rename a File If It Exceeds 1 MB In Size

Trying to write a script that renames a logfile if it exceeds roughly 1 MB.

My find command is:

Code:

find some_logfile -type f -size +20000

Now I want to do my processing if it finds a file or not...
How can I go about this? The $? is 0 if it finds a file or not.

Solution:

Please avoid running scripts containing errors in a production environment. It will bite you in the bum.

Here is a script structure which you may wish to amend to your local environment. 

Please avoid blind cut/paste/run because you need to understand what is going to happen before you run a script.

There are several riders regarding logfile maintenance scripts. If the logfile is open by a program do not rename (mv) the file. In certain circumstances you can copy then truncate the logfile, in other circumstances you must ensure that the program does not have the logfile open. It is all to easy to crash a database engine by renaming logs.

Code:

filename="some_logfile"
MB="`echo '1024 * 1024'|bc`"    # One megabyte in bytes
#
# If the file exists, find out how big it is in bytes
if [ -f "${filename}" ]
then
        filesize=`ls -lad "${filename}" | awk '{print $5}'`
else
        echo "File missing: ${filename}"
        exit 1
fi
#
# Compare the size of the file with the maximum and rename the file if it is too big
if [ ${filesize} -gt ${MB} ]
then
        echo "Renaming ${filename} ${filename}.old"
        mv "${filename}" "${filename}.old"
fi

or 

I don't know whether my understanding is correct on your requirement. But you can achieve this by a single stroke .

Code:

find . -iname "test_log" -size +1M -exec mv {} test_log_mbs \;

Have a Unix Problem
Unix Forum - Do you have a UNIX Question?

Unix Books :-
UNIX Programming, Certification, System Administration, Performance Tuning Reference Books

Return to : - Unix System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.