Write a Simple Bash Script to Automate Backups on Ubuntu
A backup script can turn a repetitive chore into a dependable part of your Ubuntu routine. Rather than remembering to copy documents, photos and project files to an external drive, you can let Bash run the same command every day or week. The result is a small, transparent system that is easier to inspect than many graphical backup tools.
This approach uses rsync, a standard Linux utility that copies files efficiently and preserves useful details such as timestamps and permissions. It can create a mirror of selected folders on another disk, while showing exactly what it is doing in the terminal. You can later expand the script with logging, automatic scheduling and email notifications.
A local backup is particularly useful for Australian households and small offices. NBN outages, accidental deletion, failing laptop drives and sudden power interruptions can all make an up-to-date copy valuable. If your files include customer details, health information or work records, remember that the Australian Privacy Act and related privacy obligations may affect how you store and protect those copies.
Choose A Backup Destination
The safest starting point is a separate physical device, such as a USB hard drive or solid-state drive. A second internal partition is more convenient, but it will not help if the computer is stolen or the main drive fails. A removable disk can be disconnected after a backup, reducing the risk of ransomware affecting both copies.
Connect the drive and open Files to identify its mount point. Ubuntu commonly mounts removable media below /media/your-user-name/, although the exact folder depends on the disk label. You can also run this command in Terminal:
lsblk -f
Look for the device that has the expected size and filesystem. Avoid guessing, because choosing the wrong destination can overwrite important data. A Linux-native filesystem such as Ext4 works well for an Ubuntu-only drive. ExFAT is more convenient if the disk must also be used with Windows or macOS, but Linux file permissions and some metadata may not transfer perfectly.
For the examples below, assume the external disk is mounted at:
/media/alex/BackupDrive
Replace alex and BackupDrive with the values shown on your own system. Do not use a path that exists only while the disk is connected unless your script checks for it first.
Select The Files Worth Copying
A backup becomes easier to maintain when it has a clear scope. Most personal files are stored in your home directory, but copying everything under /home can include browser caches, downloaded packages and other temporary data. A focused list is quicker and produces fewer confusing warnings.
Common folders to protect include:
/home/alex/Documents
/home/alex/Pictures
/home/alex/Videos
/home/alex/Music
/home/alex/Desktop
/home/alex/.config
The hidden .config folder contains settings for many applications. It can be useful when rebuilding a desktop, although it may also contain old or machine-specific settings. Application data is often stored in other hidden folders, including .local/share. Add these directories only when you know the application needs them.
Create a working folder for the script:
mkdir -p "$HOME/bin"
nano "$HOME/bin/backup-home.sh"
The mkdir command creates the folder if it does not already exist. The second command opens the Nano text editor. You can list individual source folders in the script, or copy the whole home directory while excluding temporary locations. A selective list is more approachable for a first backup and makes it clear which data is being protected.
Build The Bash Backup Script
Paste the following script into Nano:
#!/usr/bin/env bash
set -u
SOURCE="$HOME/"
DEST="/media/alex/BackupDrive/ubuntu-home/"
LOG_DIR="$HOME/backup-logs"
LOG_FILE="$LOG_DIR/backup-$(date +%F).log"
mkdir -p "$LOG_DIR"
if ! mountpoint -q "/media/alex/BackupDrive"; then
echo "Backup drive is not mounted. Backup cancelled."
exit 1
fi
mkdir -p "$DEST"
rsync -a --delete \
--exclude=".cache/" \
--exclude="Downloads/" \
"$SOURCE" "$DEST" >> "$LOG_FILE" 2>&1
if [ "$?" -eq 0 ]; then
echo "Backup completed: $(date)"
else
echo "Backup failed. Check $LOG_FILE"
exit 1
fi
Change both destination paths if your username or drive label differs. The trailing slash in SOURCE="$HOME/" means that the contents of your home directory are copied into the destination. The -a option enables archive mode, which preserves directory structure, timestamps and permissions. The log file records the output so you can investigate a failed run later.
The --exclude options skip the cache and Downloads folders. Adjust them to match your habits. If Downloads contains tax documents, work material or photos that have not been filed elsewhere, remove that exclusion. The --delete option makes the destination mirror the source by removing files from the backup when they have been removed from the home directory. That keeps the backup tidy, but it can also remove a file you deleted by mistake.
For a safer first version, omit --delete. You will retain files on the backup after deleting them from the computer, although the destination may grow over time. A mirror is useful for a clean recovery copy; a versioned backup is better for recovering older files. This simple script is a starting point rather than a complete replacement for a multi-version backup system.
Test The Script Before Scheduling It
Save the file in Nano with Ctrl+O, press Enter, then exit with Ctrl+X. Make it executable:
chmod u+x "$HOME/bin/backup-home.sh"
Run it manually while the external drive is connected:
"$HOME/bin/backup-home.sh"
The mount-point check prevents a common mistake: running rsync when the drive is absent. Without that check, a command could create /media/alex/BackupDrive/ubuntu-home/ on the computer’s own disk, giving the appearance of a successful backup while saving nothing externally.
For the first test, consider adding --dry-run to the rsync command. A dry run lists what would be copied without changing files:
rsync -a --dry-run \
--exclude=".cache/" \
--exclude="Downloads/" \
"$SOURCE" "$DEST"
Review the output carefully. Check that personal folders appear, that unwanted caches are excluded and that the destination path is correct. After a real run, open the external drive in Files and inspect several documents and images. You can compare the source and destination with:
rsync -a --dry-run --itemize-changes "$HOME/" "$DEST"
If there is no output, the two locations are currently aligned according to the selected options. If the command reports “permission denied”, the source may contain files owned by another account, or the destination filesystem may not support Linux permissions. Avoid adding sudo casually; running the whole script as root can create root-owned files that your normal account cannot easily edit.
Schedule Automatic Backups
Once the manual run works, schedule it with a user-level cron job. Open your personal crontab:
crontab -e
Add this line to run the script at 7:30 pm every evening:
30 19 * * * /home/alex/bin/backup-home.sh
Replace alex with your Ubuntu username. Cron uses a minimal environment, so absolute paths are preferable. The external disk must be connected and mounted at the expected location when the job runs. A laptop that is asleep, shut down or away from the drive will simply miss that scheduled run.
Many Australian homes have computers connected through NBN services, but this local backup does not depend on internet speed or connectivity. It can therefore continue to protect files during an NBN outage. It also avoids cloud storage fees and keeps the main copy under your control, although it does not protect against theft, fire or a disaster affecting both the computer and the drive.
For a laptop, a desktop notification or a systemd timer may be more convenient than cron because systemd can handle missed schedules more flexibly. Cron remains a sensible first choice because it is available on Ubuntu, easy to inspect and sufficient for a machine that is usually running at the chosen time.
Protect And Maintain The Backup
A mirrored backup should not be treated as an archive. If an important file is encrypted by malware or damaged and the script runs with --delete, the damaged version may replace the healthy copy. Keep a second backup with a different history, such as a rotating external disk, a trusted cloud service or a dedicated tool such as Déjà Dup, Borg or Restic.
Encryption matters when a drive leaves your home or office. Ubuntu can work with an encrypted filesystem, and many external drives can be formatted with encryption tools before use. Store the recovery passphrase somewhere safe, because a lost key can make the files permanently inaccessible. If the drive contains client records or personal information, secure storage supports good privacy practice and may be important under Australian workplace or privacy requirements.
Check the log occasionally:
tail -n 30 "$HOME"/backup-logs/backup-*.log
Run a restoration test every few months by copying a few files from the backup to a temporary folder and opening them. A backup that has never been restored is only an assumption. Replace ageing drives before they fail, keep the disk away from heat and moisture, and eject it safely after use.
You can also add a simple retention strategy by using dated destination folders instead of one mirror, but that requires additional disk space and script logic. For family photos from Melbourne, work documents in Brisbane or study files in Perth, the key principle is the same: maintain at least one recent copy and one separate copy that is not continuously attached.
A small Bash script is enough to automate a reliable first layer of protection on Ubuntu. Use a clearly identified external drive, verify the mount point, test with a dry run, read the logs and practise restoring files. The practical routine is simple: connect the backup disk, let the scheduled job run, check that it completed, then disconnect the drive and store it safely.