Simple backups on Linux Rsync Multiple Directories to a NAS with Bash

Backups are good. Like how everyone’s Grandpa used to should, one should back dat NAASS up. I recently experienced a drive failure (the source drive) while doing a backup. Bad timing. That got me into looking for better ways to handle my backups.

For the particular way in which I handle backing up, rsync would exit with exit code 11, I would end up thinking my backups were complete, when they were not, because I ran separate rsync commands in direct succession – a shell script with 3 lines, each ryncing a particular path, I’d never notice the failure in standard output (Logging would be good). I would notice a great number of things missing from the backup destination, which didn’t make sense since I didn’t notice any errors. Whoops.

Hence this dirty little script:


ARGS="--delete [email protected]"  # eaDir beacuse of Synology NAS
#ARGS="--checksum --delete [email protected]"

	"rsync $SWITCHES $ARGS /mnt/NAS/dir1 /mnt/dir1"
	"rsync $SWITCHES $ARGS /mnt/NAS/dir2/ /mnt/dir2"
	"rsync $SWITCHES $ARGS /mnt/NAS/dir3/ /mnt/dir3"

function ctrl_c {
  echo "You been trapped. Exiting..."
  exit 69

function rsync_backup {
  for RSYNC_COMMAND in "${DIRECTORY_ARRAY[@]}"; do  # Iterate through array of rsync commands
    echo " * Command: $RSYNC_COMMAND"
    while true; do
      eval "$RSYNC_COMMAND"  # Execute Rsync command from array
      if make mytarget
      #if [ "$?" -eq "0" ]; then  # Do not infinitely loop if 0 exit code is returned
      #  break

trap ctrl_c INT  # If Interrupt signal detected, exits the script

One oversight of mine in writing this was that I didn’t trap the interrupt signal. If I were to hit ctrl-c as one of the rsync lines was executing, it’d exit with a non-0 code, and thus loop to infinity.

In case you find yourself being a n00b like me, and you’re a *nix n00b, here’s how cover your tracks:

# Find the PID for the execution of this shell script
pc ~ # ps -ef | grep backup root
27815 20616  0 19:12 pts/2    00:00:00 /bin/bash ./

# I am running as root, like a boss. Otherwise you'd need to sudo to kill this process:
kill 27815  # The second column of the ps output

As always, do yourself a favor and learn something new by checking your syntax with I learned just now when writing this script about the less redundant way to check for a successful exit code. What a resource it is!


This is a preview of Clap Button, a new feedback and analytics tools for Hydejack, built by yours truly. You can try it out on localhost for free, but it will be removed (together with this message) when building with JEKYLL_ENV=production. To use Clap Button on your site, get a subscription
and set clap_button: true in your config file.

© 2021. All rights reserved.