How to backup filesystem with tar using a bash script?

ぐ巨炮叔叔 提交于 2019-12-04 12:46:05

Sandro, you might want to consider spacing things out in your script and producing individual errors. Makes things much easier to read.

#!/bin/bash

mybackupname="backup-fullsys-$(date +%Y-%m-%d).tar.gz"

# Record start time by epoch second
start=$(date '+%s')

# List of excludes in a bash array, for easier reading.
excludes=(--exclude=/$mybackupname)
excludes+=(--exclude=/proc)
excludes+=(--exclude=/lost+found)
excludes+=(--exclude=/sys)
excludes+=(--exclude=/mnt)
excludes+=(--exclude=/media)
excludes+=(--exclude=/dev)

if ! tar -czf "$mybackupname" "${excludes[@]}" /; then
  status="tar failed"
elif ! mv "$mybackupname" backups/filesystem/ ; then
  status="mv failed"
else
  status="success: size=$(stat -c%s backups/filesystem/$mybackupname) duration=$((`date '+%s'` - $start))"
fi

# Log to system log; handle this using syslog(8).
logger -t backup "$status"

If you wanted to keep debug information (like the stderr of tar or mv), that could be handled with redirection to a tmpfile or debug file. But if the command is being run via cron and has output, cron should send it to you via email. A silent cron job is a successful cron job.

The series of ifs causes each program to be run as long as the previous one was successful. It's like chaining your commands with &&, but lets you run other code in case of failure.

Note that I've changed the order of options for tar, because the thing that comes after -f is the file you're saving things to. Also, the -p option is only useful when extracting files from a tar. Permissions are always saved when you create (-c) a tar.

Others might wish to note that this usage of the stat command works in GNU/Linux, but not other unices like FreeBSD or Mac OSX. In BSD, you'd use stat -f%z $mybackupname.

The file redirection as you have it will only record the output of mv.

You can do

{ tar ... && mv ... ; } > logfile 2>&1

to capture the output of both, plus any errors that may occur.

It's a good idea to always be in the habit of quoting variables when they are expanded.

There's no need for the exit.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!