【问题标题】:Bash script: Tar not working properlyBash 脚本:Tar 无法正常工作
【发布时间】:2011-06-13 05:15:01
【问题描述】:

我刚刚将下面显示的 bash 脚本放在一起,以便从设置的文件夹进行连续备份。

然而,find 调用似乎不仅在备份中包括/home/myfoldertobackup/,而且还包括它检查文件年龄的 tar。为什么会这样?我该怎么做才能确保仅将前面提到的文件夹放入 tar 中?

if [ -e $filename ];
then
    # Tar exist. Check if tar is older than five days and if so, update it.
    find $filename -mtime +5 -exec tar -czvf $filename /home/myfoldertobackup/ {} \;
else
    #Tar doesn't exist. Force creation of tar!
    tar -czvPf $filename /home/myfoldertobackup/
fi

【问题讨论】:

  • 请注意,您的备份策略可确保如果新备份因任何原因失败,您之前的备份已被破坏 - 因此您的情况比以前更糟。在您知道新备份完成之前,请勿销毁旧备份。
  • 嗨乔纳森。绝对好点!你会说在临时位置制作焦油,然后将它们移动到备份目标位置会更合适吗?

标签: bash shell ubuntu sh


【解决方案1】:

如果 "$filename" 上次修改时间超过 5 天,find 运行以下命令:

tar -cvfz $filename /home/myfoldertobackups/ $filename

将 /home/myfoldertobackup $filename(可能被截断,因为 tar 将在其上写入)放入 $filename;如果你不想要 $filename 就写

find $filename -mtime +5 -exec tar -cvz /home/myfoldertobackups -f {} \;

或更好(因为更具可读性)

if [ -n "$(find $filename -mtime +5)" ]; then
    tar -cvzf "$filename" /home/myfoldertobackups;
fi

更新

这是您的代码以及我提出的更改:

if [ -e $filename ];
then
    # Tar exist. Check if tar is older than five days and if so, update it.
    # find $filename -mtime +5 -exec tar -czvf $filename /home/myfoldertobackup/ {} \;
    if [ -n "$(find $filename -mtime +5)" ]; then
        tar -cvzf "$filename" /home/myfoldertobackups;
    fi
else
    #Tar doesn't exist. Force creation of tar!
    tar -czvPf $filename /home/myfoldertobackup/
fi

【讨论】:

  • 嗨,马可!非常感谢。我可能有点迟钝,但您的解决方案是否考虑到该文件也可能不存在的事实?
  • 不,你没有问题:我的解决方案只替换了 find 命令;无论如何,我会用完整的代码更新我的答案:)
  • 嗨,马可。非常感谢您的帮助!
【解决方案2】:

那是因为find 替换了{} 为其找到的文件的名称。 只需删除{} 即可完成。

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2014-12-07
    • 2015-04-04
    相关资源
    最近更新 更多