How to create tar for files older than 7 days using linux shell scripting


I’m writing shell script to backup files older than 7 days. Here is my code. But i’m not getting expected result. Can anyone correct me?

# Backup files

files=($(find /var/log/ -mtime +"7"))
 for files in ${files[*]}
         echo $files
         tar cvfz backup.tar.gz $files


This will work:

while IFS=  read -r -d $'\0'; do
done < <(find /var/log/ -mtime +7 -print0)
tar cvfz backup.tar.gz "${files[@]}"

Note the use of "${files[@]}" as opposed to ${files[*]}. "${files[@]}" will expand to provide tar with one argument per file name and will work even if the file names contain spaces, tabs, or newlines. By contrast, after the shell expands ${files[*]}, it will perform word splitting, potentially mangling your file names.

For a detailed explanation of the loop used to create the files array, see: How can I store find command result as arrays in Bash

All files and directories produced by the command find /var/log/ -mtime +7 will be included in the tar file. To include only files, not directories, see Skynet’s answer.

To archive logs from the seven most recent days

Only one character need change:

while IFS=  read -r -d $'\0'; do
done < <(find /var/log/ -mtime -7 -print0)
tar cvfz backup.tar.gz "${files[@]}"

This works because find interprets numeric arguments as follows:

Numeric arguments can be specified as
+n for greater than n,
-n for less than n,
n for exactly n.

Thus, -mtime +7 means greater than 7 days old while -mtime -7 means less than 7. Note that find will ignore fractional parts. Thus +7 will include 8 days old but not 7.5 days old. See man find for details.

Answered By – John1024

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published