mgr
mgr

Reputation: 651

How to create zip/gz/tar files for if the files are older than particular days in UNIX or Linux

I need a script file for backup (zip or tar or gz) of old log files in our unix server (causing the space problem). Could you please help me to create the zip or gz files for each log files in current directory and sub-directories also?

I found one command which is to create gz file for the older files, but it creates only one gz file for all older file. But I need individual gz file for each log file.

find /tmp/log/ -mtime +180 | xargs  tar -czvPf  /tmp/older_log_$(date +%F).tar.gz

Thanking you in advance.

Upvotes: 10

Views: 93141

Answers (3)

Shiva
Shiva

Reputation: 171

Best way is

find . -mtime +3 -print -exec gzip {} \;

Where +3 means zip all files which is older than 3 days.

Upvotes: 17

mgr
mgr

Reputation: 651

Thanks a lot for your reply. I got it.

files=($(find /tmp/mallik3/ -mtime +"$days"))
for files in ${files[*]}
do
     echo $files
     zip $files-$(date --date="- "$days"days" +%F)_.zip $files
      #       tar cvfz $(files)_$(date --date='-6months' +%F).tar.gz $files
#       rm $files
done

Upvotes: 7

William Pursell
William Pursell

Reputation: 212298

First, the -mtime argument does not get you files that are "older" than a certain amount. Rather, it checks the last time the file was modified. The creation date of files is not kept in most file systems. Often, the last modified time is sufficient, but it is not the same as the age of the file.

If you just want to create a single tar file for each archive, use -exec instead of passing the data to xargs:

find /tmp/log/ -mtime +180 -type f -exec sh -c \
    'tar -czvPf /tmp/older_log_$(basename $0)_$(date +%F).tar.gz $0' {} \;

Upvotes: 5

Related Questions