- Published on
Automating Backups rsync macOS: Some Simple Steps to Secure Your Data
Data is everything, safeguarding your important files is crucial. Whether you're a developer, a student, or someone who loves digital organization, having an automated backup system helps you secure your data and offers peace of mind.
rsync is a powerful tool that has gained immense popularity for backup solutions. Here's why:
The first step is creating a backup Bash script. Here's a simple example:
shell#!/bin/bash# Define common exclusionsEXCLUDES=('*.log''*/tmp''*/__pycache__''*/node_modules''*/.yarn''*/.venv''*/venv''*/.terraform''*/.terragrunt''*/.git''*/.next''*/build''*/vendor''.DS_Store''.localized''.Spotlight-V100''.Trashes''.fseventsd')# Convert exclusions to rsync formatRSYNC_EXCLUDES=""for EXCLUDE in "${EXCLUDES[@]}"; doRSYNC_EXCLUDES+="--exclude='$EXCLUDE' "done# Define source and destination pathsSOURCES=("/Users/user/workspace/work/*""/Users/user/workspace/personal/*")DESTINATIONS=("/Volumes/Backup/ws-work""/Volumes/Backup/ws-personal")# Perform rsync operationsfor i in "${!SOURCES[@]}"; doecho "Syncing ${SOURCES[$i]} to ${DESTINATIONS[$i]} ..."echo "rsync -avh $RSYNC_EXCLUDES ${SOURCES[$i]} ${DESTINATIONS[$i]}"# The eval command is used to correctly interpret and execute the constructed rsync command string with the dynamically generated exclusion patterns.eval rsync -avh $RSYNC_EXCLUDES "${SOURCES[$i]}" "${DESTINATIONS[$i]}"done
The script initializes arrays for SOURCES (the files you want to backup) and DESTINATION (where to store the backups).
Step 2: Making the Script Executable
You’ll need to make your script executable. Simply run the following command in your Terminal:
shellchmod +x /path/to/backup.sh
Now that the script is ready, the next phase is to set up a schedule for your backups. In macOS, you can use cron or launchctl.
Alternatively, you can use launchctl by creating a property list file:
xml<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>Label</key><string>com.user.backup</string><key>ProgramArguments</key><array><string>/path/to/backup.sh</string></array><key>StartCalendarInterval</key><dict><key>Hour</key><integer>3</integer> <!-- 3 AM --><key>Minute</key><integer>0</integer> <!-- 0 minutes --></dict><!-- Log output paths --><key>StandardOutPath</key><string>/path/to/backup_stdout.log</string><key>StandardErrorPath</key><string>/path/to/backup_stderr.log</string></dict></plist>
Load the job with:
shelllaunchctl load ~/Library/LaunchAgents/com.user.backup.plist
By automating your backups with rsync on macOS, you're taking a proactive measure to protect your data. Now, every day at 3 AM, your files will sync to your external hard drive, allowing you to enjoy life without worrying about losing anything important.