SEC.OPSBack to Portfolio→
Linux ServicesCompleted

In the Quest to Learn Linux Services, I Ended Up Building Resilient Backup Automation: From an rclone Script to a systemd Service

A walkthrough of building an automated, multi-directory backup pipeline with rclone and systemd — silent failures, per-user config traps, a lowercase directive that quietly ran a service as root, and why rclone sync needs --backup-dir before you trust it with anything named Backups.

Kamau James
August 2026
Technical / Educational
LinuxsystemdrcloneBackup AutomationBash

Building Resilient Backup Automation: From an rclone Script to a systemd Service

Linux Service Analyst: Kamau James | Date: August 2026 | Classification: Training / Educational


Executive Summary

Whether you're hosting a web application, setting up a backup script, or hunting persistence achieved by installing a service on Linux, knowing how to create Linux service files is a fundamental skill for any Linux administrator, developer, or threat hunter. Not every SOC skill gets exercised during an investigation. Some of it shows up in the quiet work of making sure the infrastructure around you actually holds up: logs that persist across reboots, backups that survive an accidental delete, services that run with the privilege they're supposed to have and nothing more.

This post builds an automated, multi-directory backup pipeline using rclone and systemd, from a single sync script to a boot-time service, including every place it broke and what that revealed.

KEY INSIGHT: Every failure in this build was silent, or pointed at the wrong cause. An empty log file, a status=1/FAILURE in the journal, a lowercase letter in a unit file — none of them announced what was actually wrong. The habit that solved all of it was the same one every time: stop guessing, go verify directly. Things this project touched that are core to understanding Linux services include: unit file sections, systemctl as an inspection tool, service types, and privilege and identity.


Section 1 — The Goal

The objective was simple on paper: take a handful of local document folders — audit resources, CV collections, compliance docs, SOC reference material — and mirror each one to its own folder in cloud storage, automatically, every time the machine booted.

In practice it touched shell scripting discipline, file permissions, systemd unit syntax, and a backup design decision that almost undermined the entire point of having a backup in the first place.


Section 2 — Understanding Linux Services (Daemons)

In Linux and Unix, a service (often called a daemon) is a program that runs continuously in the background. Unlike applications that require user interaction, daemons start automatically when the system boots up, run silently without an attached terminal, and wait for specific events or requests.

Common examples include web servers (nginx, apache2), database servers (mysql, postgresql), and remote access tools (sshd). Daemons typically end with the letter "d" to signify their background nature.

The Evolution of Linux Init Systems

To understand how to create a Linux service configuration today, it helps to understand how Linux manages them. The very first process started by the Linux kernel upon booting is the init system (always assigned Process ID 1). This system is responsible for starting other services. It continues running until the system is shut down.

It is the direct or indirect ancestor of all other processes and automatically adopts all orphaned processes; in most Unix-like systems, a kernel panic will occur if the kernel is unable to start it or if it dies for any reason.

Historically, Linux used SysVinit (System V init). Administrators had to write complex, lengthy Bash shell scripts placed in /etc/init.d/ and manage "runlevels" to dictate boot order.

The majority of modern Linux distributions (including Ubuntu, Debian, RHEL, CentOS, and Fedora) have standardized on a much more powerful and unified init system called systemd.

What Is systemd?

systemd is a suite of basic building blocks for a Linux system, acting primarily as an initialization system and service manager. It was designed to overcome the limitations of SysVinit by offering:

  • Parallelization: It can start multiple services at the same time, significantly reducing boot times.
  • On-demand starting: It can defer starting a service until a specific socket or hardware is accessed.
  • Dependency management: It strictly understands which services rely on others.
  • Process tracking: It uses Linux control groups (cgroups) to track processes, meaning a service can't escape being stopped by "forking" itself twice.

Because systemd is the modern standard, when you create a Linux service today, it means writing a systemd unit file.

Service Configuration: Structure of a Unit File

In the systemd environment, a configuration file that defines a service is called a unit file. These files are declarative — meaning you simply state what you want the service to do, rather than writing a complex script telling it how to do it.

A standard unit file is divided into three main sections:

  • [Unit]: Contains metadata and dependencies. It describes what the unit is, its documentation, and its relationship to other units (e.g., start this after the network is up).
  • [Service]: Contains the specific configuration for the service itself. This includes the command to execute, the user to run as, and how to handle restarts if the service crashes.
  • [Install]: Dictates behavior when the unit is enabled or disabled. It tells systemd which "target" (system state) should trigger this service to start on boot.

Types of System Services (Unit Types)

  • .service: A standard system service (a background process).
  • .socket: Used for socket-based activation. systemd listens on a port and starts the associated .service only when traffic arrives.
  • .timer: A systemd timer that acts like a cron job, triggering a service at specific times or intervals.
  • .target: A logical grouping of units, used to represent a system state (e.g., multi-user.target is the equivalent of a fully booted system without a GUI).
  • .mount: Controls mounting directories in the file system.

Understanding Dependencies and Boot Order

One of systemd's greatest strengths is how it handles boot order. You configure this in the [Unit] section using specific directives:

  • Requires=: A hard dependency — if your service requires Service B, and Service B fails or stops, your service will also be stopped.
  • Wants=: A soft dependency — if your service wants Service B, systemd will try to start Service B; however, if Service B fails, your service will still continue to run. (This is generally preferred over Requires=.)
  • After= / Before=: These dictate order, not dependencies. If you use After=network.target, systemd guarantees the network target is reached before it attempts to start your service.

Section 3 — Starting Point: A Single Sync Script

To keep this post shorter, I skipped the rclone installation and Google Drive API setup steps. The first version was a straightforward wrapper around rclone sync, using strict bash mode so the script would fail loudly instead of limping along after an error:

#!/usr/bin/env bash
set -euo pipefail

SOURCE_DIR="$HOME/Documents/Backups"
REMOTE_DEST="Backup_svc:backups"
LOG_FILE="$HOME/.config/rclone/logs/backup.log"

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting backup..." >> "$LOG_FILE"

rclone sync "$SOURCE_DIR" "$REMOTE_DEST" \
    --log-file="$LOG_FILE" \
    --log-level INFO \
    --transfers 4 \
    --checkers 8 \
    --fast-list

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Backup completed successfully." >> "$LOG_FILE"

set -euo pipefail is worth calling out on its own:

FlagEffect
-eExit immediately if any command fails
-uTreat unset variables as an error
-o pipefailFail a pipeline if any stage of it fails

It's a small habit that pays for itself the moment something goes quietly wrong.


Section 4 — Moving to /opt: The First Real Bug

Once the script worked, the next step was making it system-owned rather than tied to a single user's home directory, which meant relocating it to /opt/backup-rclone/. This is where the first real debugging session started.

Running the script produced nothing — no output, no error, an empty log file. The instinct here matters as much as the fix: rather than guessing, the right move was to trace execution directly.

bash -x bin/backup-rclone.sh

The trace showed the script running fine, right up to:

+ LOG_FILE=/home/hanzo/opt/backup-rclone/logs/backup.log

The bug was a leftover $HOME reference in the log path. The script was quietly writing logs to a completely different directory than the one being checked. Nothing was broken in the sync logic at all — it just wasn't writing where anyone was looking.

LESSON: When a script produces zero output and zero errors, that is not proof it did nothing. It is a sign to trace execution rather than assume the failure point.


Section 5 — The Config Mismatch: A Lesson in Per-User State

With the log path fixed, a new and more informative error appeared:

NOTICE: Config file "/root/.config/rclone/rclone.conf" not found - using defaults
CRITICAL: Failed to create file system for "Backup_svc:backups": didn't find section in config file ("Backup_svc")

The script had been run as root, but the rclone remote (Backup_svc) had been configured under a regular user account. rclone configuration is per-user by default, so root looking for it found nothing. Running the same script as the correct user immediately worked:

sudo -u hanzo bin/backup-rclone.sh

This is a small thing that scales into a real operational risk. A backup, monitoring, or automation script that silently runs as the wrong user does not always fail this loudly. Sometimes it just runs with the wrong permissions, or against the wrong configuration, and nobody notices until the day it matters.


Section 6 — Automating with systemd, and a Lowercase Letter That Broke Everything

With the script working manually, the next step was wiring it into systemd so it would run automatically at boot:

[Unit]
Description=Rclone backup of Documents/Backups on boot
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
User=hanzo
ExecStart=/opt/backup-rclone/bin/backup-rclone.sh

[Install]
WantedBy=multi-user.target

After=network-online.target and Wants=network-online.target matter more than they look. Without them, systemd may start the service before the network is actually up, and a sync job that depends on reaching a remote server will fail for reasons that have nothing to do with the script itself.

The service still failed. The journal only said Main process exited, code=exited, status=1/FAILURE — a symptom, not a cause. The actual reason was sitting in the unit file itself:

user=hanzo

Lowercase. systemd directives are case sensitive, and user= is not a directive systemd recognizes.

Normal vs. Abnormal

# ✅ Correct — systemd recognizes this directive
User=hanzo
# ❌ Silently ignored — not a recognized directive
# Service falls back to running as root
user=hanzo

FINDING: systemd did not warn about the unrecognized directive. It did not error. It just quietly defaulted to running the service with more privilege than intended. A subtly wrong or altered User= line in a unit file that nobody notices because there is no error is exactly the kind of thing worth checking for when reviewing services on a system that is not your own.


Section 7 — Deploying the Service: daemon-reload and Verification

Writing the unit file isn't enough on its own. Every time a unit file is created or edited, systemd needs to be told to notice:

sudo systemctl daemon-reload

This forces systemd to re-read all unit files from disk, update its internal configuration, and rebuild the dependency tree. Without running this command, systemd will not recognize the new service — or any modification to an existing one — even if you try to start or enable it immediately afterward.

With the daemon reloaded, the next step was confirming systemd actually saw the new unit:

hanzo@Hashashi:~$ systemctl list-unit-files | grep backup_svc.service
backup_svc.service                                            enabled         enabled
hanzo@Hashashi:~$

From there, the service was enabled (so it runs on every boot) and started manually for an immediate test run:

sudo systemctl enable backup_svc.service
sudo systemctl start backup_svc.service

To confirm the run actually succeeded, the first place to check was the script's own log file:

cat /opt/backup-rclone/logs/backup.log
Transferred:   	   31.993 MiB / 31.993 MiB, 100%, 816.203 KiB/s, ETA 0s
Checks:                 0 / 0, -, Listed 14
Transferred:           14 / 14, 100%
Elapsed time:        41.5s
[2026-08-26 14:55:46] Backup run completed successfully.
[2026-08-26 20:52:16] Starting backup run...
[2026-08-26 20:52:16] Syncing Audit-Resources -> Backup_svc:Audit-Resources
2026/08/26 20:52:24 INFO  : There was nothing to transfer
...
[2026-08-26 20:52:40] Backup run completed successfully.

Later runs correctly report There was nothing to transfer for each folder — expected, since nothing had changed locally since the previous sync. That line is a healthy result, not a failure.

The service's own systemd-level activity can also be checked independently of the script's log file, via the journal:

sudo journalctl -u backup_svc.service

This is worth doing even when the script's log file looks fine, since the journal captures anything systemd itself has to say about the unit — exit codes, restarts, timing — separately from whatever the script chose to write out itself.

A QUIET SECOND TYPO: While confirming the deployed unit file with cat /etc/systemd/system/backup_svc.service, the [Unit] section read Decription= instead of Description=. Unlike the earlier user= / User= mistake, this one isn't functionally destructive — Description= only supplies the human-readable text shown by systemctl status, so the service still ran correctly with it misspelled. But it's the same failure pattern in miniature: an unrecognized directive doesn't error, it's just silently dropped. systemctl cat <service> is cheap enough to run after every edit that there's no good reason to skip it.


Section 8 — The Part That Almost Undermined the Whole Project

The script used rclone sync, which makes the destination match the source exactly, including deletions. That's by design, and it's also a trap. The very first successful log run demonstrated it directly:

INFO  : AI_data_specialist.pdf: Deleted

Delete a file locally, and on the next run it disappears from the cloud copy too. For a folder literally named "Backups," that defeats the purpose. A backup that faithfully mirrors an accidental deletion is not protecting against accidental deletion.

# ❌ Destructive — deletions propagate to the remote with no recovery path
rclone sync "$SOURCE_DIR" "$REMOTE_DEST" \
    --log-file="$LOG_FILE" \
    --log-level INFO
# ✅ Safe — deleted files are archived, not destroyed
rclone sync "$SOURCE_DIR" "$REMOTE_DEST" \
    --backup-dir="${REMOTE_NAME}:${dir}-deleted/$(date '+%Y-%m-%d')" \
    --log-file="$LOG_FILE" \
    --log-level INFO

--backup-dir tells rclone to move anything that would be deleted into a separate, dated archive folder instead of deleting it outright. The live folder stays a clean, current mirror of the local directory. Anything removed locally still exists, recoverable, under a dated folder like SOC-Resources-deleted/2026-08-26/. It's a small addition that turns a mirror into an actual safety net.


Section 9 — Scaling to Multiple Directories

The final version moved from a single source and destination to a loop over a list of named folders, each syncing to its own matching remote folder with its own deleted-file archive:

#!/usr/bin/env bash
set -euo pipefail

REMOTE_NAME="Backup_svc"
LOG_FILE="/opt/backup-rclone/logs/backup.log"

DIRS=(
    "Audit-Resources"
    "CVs-collection"
    "GOK-DOCs"
    "SOC-Resources"
)

BASE_DIR="/home/hanzo/Documents/Backups"

mkdir -p "$(dirname "$LOG_FILE")"
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting backup run..." >> "$LOG_FILE"

for dir in "${DIRS[@]}"; do
    SOURCE_DIR="$BASE_DIR/$dir"
    REMOTE_DEST="${REMOTE_NAME}:${dir}"

    if [ ! -d "$SOURCE_DIR" ]; then
        echo "[$(date '+%Y-%m-%d %H:%M:%S')] WARNING: $SOURCE_DIR does not exist, skipping." >> "$LOG_FILE"
        continue
    fi

    echo "[$(date '+%Y-%m-%d %H:%M:%S')] Syncing $dir -> $REMOTE_DEST" >> "$LOG_FILE"

    rclone sync "$SOURCE_DIR" "$REMOTE_DEST" \
        --backup-dir="${REMOTE_NAME}:${dir}-deleted/$(date '+%Y-%m-%d')" \
        --log-file="$LOG_FILE" \
        --log-level INFO \
        --transfers 4 \
        --checkers 8 \
        --fast-list
done

echo "[$(date '+%Y-%m-%d %H:%M:%S')] Backup run completed successfully." >> "$LOG_FILE"

The existence check before each sync matters as much as the loop itself. With set -e active, one missing folder would otherwise kill the entire run and skip every directory after it. Instead, a missing folder logs a warning and the script moves on — the difference between a partial success and a silent total failure.

Even this had one more lesson waiting. The first run produced four warnings: every folder reported missing, despite all four existing and being spelled correctly.

WARNING: /home/hanzo/Documents/Audit-Resources does not exist, skipping.
WARNING: /home/hanzo/Documents/CVs-collection does not exist, skipping.
WARNING: /home/hanzo/Documents/GOK-DOCs does not exist, skipping.
WARNING: /home/hanzo/Documents/SOC-Resources does not exist, skipping.

The base path in the script pointed at ~/Documents, while the folders actually lived one level deeper, at ~/Documents/Backups. This was confirmed with a quick directory listing and fixed with a one-line path change — a reminder that "the names are right" and "the path is right" are two different things worth checking separately.


Section 10 — Where This Connects to Verification Discipline

The habit that actually solved every bug in this build was the same one each time: stop guessing, go verify directly.

QuestionCommand
What is the script actually doing?bash -x bin/backup-rclone.sh
Who is a process actually running as?/proc/<pid>/exe, systemctl show -p MainPID
What does the unit file actually say?systemctl cat <service>
Did systemd pick up my latest edit?sudo systemctl daemon-reload, then systemctl list-unit-files | grep <service>
Does that remote folder actually exist as named?rclone lsd <remote>:

That's a small, unglamorous version of the same discipline that shows up in incident response: do not trust the label on the tin, verify the contents.


High-Value Failure Modes: Quick Reference

SymptomReal CauseHow It Was Found
Empty log, no outputStray $HOME reference writing logs to the wrong pathbash -x trace
didn't find section in config fileScript run as root, rclone remote configured under a regular userReading the error, checking whoami vs. config location
status=1/FAILURE in journalLowercase user= instead of User= in the unit filesystemctl cat on the unit
Files vanish from remote after local deletionrclone sync mirrors deletions by defaultReading the sync log line by line
Every folder reported "does not exist"Base path one directory level too shallowDirectory listing (ls) against the script's assumed path

Key Takeaways from Day 1

Silence is not success. None of the bugs in this build were exotic — a stray $HOME, a per-user config file, a lowercase letter in a systemd directive, a sync mode with a destructive default, a base path one level off. What ties them together is that every single one failed silently, or failed with an error message that pointed somewhere other than the real cause.

A fact is not an explanation. status=1/FAILURE in a systemd journal is a fact, not an explanation. An empty log file is a fact, not proof of nothing happening.

Mirrors are not backups. rclone sync without --backup-dir faithfully reproduces an accidental deletion on the remote. A backup that mirrors deletions defeats its own purpose.

Verify, don't assume. Trace the script with bash -x. Check who a process is actually running as. Read the unit file back rather than trusting memory of what was typed. Confirm a remote folder's exact name rather than assuming it matches. This is the same discipline that shows up in incident response, applied to infrastructure that's supposed to be boring.

← Back to All Work→