从 cron 电子邮件中删除 tar 压缩线轴

从 cron 电子邮件中删除 tar 压缩线轴

我有一个 crontab 作业,它调用一个简单的脚本来备份网站:

15 0 1,10,20 * * /home/username/bin/backup_whatever

这是脚本:

#!/bin/bash
TODAY=$(date +"%Y%m%d")
FILE_TO_PUT="filename.$TODAY.tar.gz"
rm -rf /home/username/filename.tar.gz
tar -zcvf /home/username/filename.tar.gz -C / var/www/website/
s3cmd put /home/username/filename.tar.gz s3://s3bucket/backups/$FILE_TO_PUT

由于 tar 命令压缩大量文件,因此执行此命令时收到的电子邮件非常大。我怎样才能只显示一条消息压缩成功而是 tar 命令的完整输出?

如果我做这样的事情会好吗?找不到 tar 返回代码。

EXITCODE=$(tar -zcvf /home/username/filename.tar.gz -C / var/www/website/)
if [ $EXITCODE -eq 0]
then
    echo "compression successfully"
else
    echo "compression unsuccessfully"
fi

答案1

tar 退出代码记录在“信息”手册中 - 用于info tar阅读有关 tar 的所有内容。 (您可以使用 阅读有关“信息”的信息info info)。似乎有 3 个(主要)退出代码。从info tar文档中:

Possible exit codes of GNU 'tar' are summarized in the following
table:

0
     'Successful termination'.

1
     'Some files differ'.  If tar was invoked with '--compare'
     ('--diff', '-d') command line option, this means that some files in
     the archive differ from their disk counterparts (*note compare::).
     If tar was given '--create', '--append' or '--update' option, this
     exit code means that some files were changed while being archived
     and so the resulting archive does not contain the exact copy of the
     file set.

2
     'Fatal error'.  This means that some fatal, unrecoverable error
     occurred.

   If 'tar' has invoked a subprocess and that subprocess exited with a
nonzero exit code, 'tar' exits with that code as well.  This can happen,
for example, if 'tar' was given some compression option (*note gzip::)
and the external compressor program failed.  Another example is 'rmt'
failure during backup to the remote device (*note Remote Tape Server::).

如果您只想收到您选择的成功或失败消息,我建议您执行以下操作:

tar zcf /home/username/filename.tar.gz -C / var/www/website/ >/dev/null 2>&1
case $? in
    0)
        printf "Complete Success\n"
        ;;
    1)
        printf "Partial Success - some files changed\n"
        ;;
    *)
        printf "Disaster - tar exit code $?\n"
        ;;
esac

tar 的调用将标准输出和错误传输到 /dev/null(也称为位桶)。然后,$?该语句会解析保存最近执行的前台管道的退出状态的特殊参数,case以输出相关消息。

相关内容