"how to backup filesystem with tar using a bash script?" Code Answer


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


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.

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

# 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.

By bheeshmar on April 7 2022

Answers related to “how to backup filesystem with tar using a bash script?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.