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

I am writing a shell script to backup files older than 7 days. Here is my code. But I do not get the expected result. Can anyone fix me?

#!/bin/bash # Backup files files=($(find /var/log/ -mtime +"7")) for files in ${files[*]} do echo $files tar cvfz backup.tar.gz $files done 
+6
source share
2 answers

The cycle will cause problems. This will work:

 #!/bin/bash files=($(find /var/log/ -mtime +7)) tar cvfz backup.tar.gz "${files[@]}" 

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

All files created by 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 last seven days

Change only one character:

 #!/bin/bash files=($(find /var/log/ -mtime -7)) 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 is less than n
n for exactly n.

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

+10
source

Replace the find this and try again,

 find /var/log -type f -mtime +7 
+3
source

Source: https://habr.com/ru/post/981640/


All Articles