Shell脚本为7天以上的文件创建tar

Shell脚本为7天以上的文件创建tar

本文介绍了如何使用Linux Shell脚本为7天以上的文件创建tar的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写Shell脚本来备份7天以上的文件.这是我的代码.但是我没有得到预期的结果.谁能纠正我?

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?

#!/bin/bash
# Backup files

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

推荐答案

这将起作用:

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

请注意,使用"${files[@]}"而不是${files[*]}. "${files[@]}"将展开以为tar每个文件名提供一个参数,并且即使文件名包含空格,制表符或换行符也将起作用.相比之下,shell扩展${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.

有关用于创建files数组的循环的详细说明,请参见:如何将查找命令结果存储为数组在Bash中

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

由命令find /var/log/ -mtime +7生成的所有文件和目录都将包含在tar文件中.要仅包括文件而不包括目录,请参阅天网的答案.

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.

只需更改一个字符:

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

之所以可行,是因为find将数字参数解释如下:

This works because find interprets numeric arguments as follows:

因此,-mtime +7表示大于7天,而-mtime -7表示小于7天.请注意,find将忽略小数部分.因此,+7将包括8天,但不包括7.5天.有关详细信息,请参见man find.

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.

这篇关于如何使用Linux Shell脚本为7天以上的文件创建tar的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 07:32