Course contentsShow
← Linux
Lesson 1310 of 1,81911. Automation and System SchedulingFree lesson

State Persistence across Reboots

Use /var/lib state files to maintain counters or status across intermittent executions.

In this lesson, you will learn how to maintain continuity in your automated background tasks by storing status data in /var/lib so your scripts can "remember" their progress even after a system reboot.

The Problem of Transient Automation

When you build automation—such as a task that processes log files or triggers an action every tenth time a systemd unit runs—the memory of those events is typically wiped whenever the machine shuts down. If your script relies on a simple variable or a temporary file in /tmp, you lose your progress, causing tasks to reset or double-process data.

Leveraging /var/lib for Persistent State

The Linux Filesystem Hierarchy Standard reserves /var/lib for persistent data that services modify during runtime. Unlike /tmp or /run, data stored in /var/lib/your-service-name/ survives reboots. To create a reliable automation loop, your script should read from and write to a "state file" in this directory.

Consider a service that performs a "cleanup" task only after ten successful check-ins:

#!/bin/bash
STATE_FILE="/var/lib/my-automation/counter"

# Ensure the directory exists
mkdir -p "$(dirname "$STATE_FILE")"

# Read the previous count or default to 0
count=$(cat "$STATE_FILE" 2>/dev/null || echo 0)

# Increment and save
count=$((count + 1))
echo "$count" > "$STATE_FILE"

if [ "$count" -ge 10 ]; then
    echo "Performing heavy task..."
    echo 0 > "$STATE_FILE" # Reset the counter
fi

Best Practices for Persistence

  1. Atomic Writes: Always write to a temporary file first and then mv it to your target state file. This prevents the state file from becoming corrupted if the system loses power mid-write.
  2. Permissions: Ensure your systemd unit service user has ownership of the directory within /var/lib. You can use the StateDirectory= directive in your systemd service file to handle this automatically: StateDirectory=my-automation
  3. Parsability: Keep your state files simple. Plain text files containing a single integer or a JSON object are easier to debug and less prone to parsing errors than complex binary formats.

By offloading your "memory" to /var/lib, you transform intermittent execution into a cohesive, reliable workflow that resumes exactly where it left off.

Key Takeaway: Use the /var/lib directory to store service state files, ensuring your automated tasks maintain their progress across system reboots.