Schedule maintenance for a Linux practice directory

Schedule cache cleanup with cron, configure execution times, inspect logs, and verify the results.

🎯 Introduction

Suppose a Node.js service generates temporary cache files daily. Without cleanup, they accumulate and consume disk space. Logging in to delete them every day is repetitive and easy to forget.

Linux provides cron: specify which command to run and when, and the system runs it on schedule.

This article schedules cleanup of old cache files in a practice directory. You will configure execution times, run a cleanup script, and verify execution through logs and files. All deletion is restricted to the practice directory you create.


🧱 Run commands on a schedule

cron is a Linux service that runs commands at specified times. A crontab stores a user's scheduled tasks: cron reads the times and commands and executes them according to those rules.

Check that cron is available

On Ubuntu, first check for crontab:

command -v crontab

A path such as /usr/bin/crontab means the command is installed. If there is no output, install cron:

sudo apt update
sudo apt install cron

Start cron and enable it at boot:

sudo systemctl enable --now cron.service

Then check whether it is running:

systemctl is-active cron.service

Normally, you will see:

active

This confirms that cron is running, but does not mean a scheduled task has been added.

Read the schedule fields

A task in a user's crontab has this basic format:

minute hour day-of-month month day-of-week command

The first five fields determine when to run the command that follows:

Field positionMeaningCommon range
1Minute0–59
2Hour0–23
3Day of month1–31
4Month1–12
5Day of week0–7; both 0 and 7 mean Sunday

* imposes no restriction on that field. For example:

15 3 * * *       Run daily at 03:15
*/5 * * * *      Run at minutes 0, 5, 10, …, 55
* * * * *        Run every minute

cron follows the server's configured time; inspect it with date. Ordinary cron generally does not catch up on tasks missed while the server was off. See the Ubuntu crontab manual for more rules.


🛠 Preview cleanup and verify it manually

Before scheduling anything, make sure the cleanup command works. Operate only on ~/linux-lab/cache here.

Prepare practice files

mkdir -p "$HOME/linux-lab/bin" "$HOME/linux-lab/logs" "$HOME/linux-lab/cache"
touch -d '2 days ago' "$HOME/linux-lab/cache/expired.tmp"
touch "$HOME/linux-lab/cache/recent.tmp"
  • mkdir -p creates directories for scripts, logs, and cache files.
  • touch -d '2 days ago' sets expired.tmp's modification time to two days ago, simulating old cache without actually waiting.
  • touch creates recent.tmp with the current modification time, simulating fresh cache.

Preview files selected for cleanup

find "$HOME/linux-lab/cache" -maxdepth 1 -type f -name '*.tmp' -mmin +1440 -print

The command means:

ArgumentPurpose
find "$HOME/linux-lab/cache"Search the practice cache directory.
-maxdepth 1Search only this level, without entering subdirectories.
-type fSelect regular files only.
-name '*.tmp'Select filenames ending in .tmp.
-mmin +1440Select files modified more than approximately 24 hours ago.
-printPrint matching paths without deleting anything yet.

Example output; username and path depend on your environment:

/home/ubuntu/linux-lab/cache/expired.tmp

Only the old file appears, confirming the intended selection. Preview with -print before deleting to avoid removing the wrong files.

Save the cleanup command as a script

Create ~/linux-lab/bin/purge-cache.sh with Vim and enter the following: purge-cache.sh.

purge-cache.sh
#!/bin/bash

cache_dir="$HOME/linux-lab/cache"
if [[ ! -d "$cache_dir" ]]; then
    printf 'Skip missing cache directory: %s\n' "$cache_dir"
    exit 0
fi

printf '[%s] Checking %s\n' "$(date -Is)" "$cache_dir"
find "$cache_dir" -maxdepth 1 -type f -name '*.tmp' -mmin +1440 -print -delete

The script first checks whether the cache directory exists. If not, it prints a message and exits. Otherwise, it logs the check's time and directory, then performs cleanup.

Compared with the preview command, this adds -delete: matching files are actually deleted. Only old .tmp files at the first level of the practice directory are affected; other files are excluded.

Run the script manually first:

bash "$HOME/linux-lab/bin/purge-cache.sh"

Example output:

[2026-11-12T15:00:00+08:00] Checking /home/ubuntu/linux-lab/cache
/home/ubuntu/linux-lab/cache/expired.tmp

This shows that the script checked the directory and found a file to delete. Inspect what remains:

ls "$HOME/linux-lab/cache"

Expected output:

recent.tmp

The old cache is gone and the fresh file remains. We have verified that the script itself works before scheduling it with cron.


🧰 Add a task and inspect its execution history

Add a test task that runs every minute

Open the current regular user's crontab:

VISUAL=vim EDITOR=vim crontab -e

crontab -e edits this user's scheduled tasks. VISUAL=vim EDITOR=vim selects Vim for this invocation. Preserve existing tasks and append:

* * * * * /bin/bash "$HOME/linux-lab/bin/purge-cache.sh" >> "$HOME/linux-lab/logs/cleanup.log" 2>&1

This rule runs the script every minute. Its parts are:

  • /bin/bash: Explicitly runs the script with Bash.
  • >> .../cleanup.log: Appends normal output to the log, preserving previous content.
  • 2>&1: Writes errors to the same log for troubleshooting.

cron's background environment may differ from your terminal. It may have a different PATH, the list of command search directories, and a different working directory. This is why the rule specifies /bin/bash and uses $HOME for the task user's home directory. Do not depend on your terminal's current directory.

The first crontab -e may ask you to select an editor. Preserve existing tasks. In particular, do not use crontab -r to remove one task: it removes the current user's entire crontab.

Save and exit, then run:

crontab -l

Seeing the new rule confirms that it was saved.

Confirm that cron actually cleaned up

The manual run already removed expired.tmp. Recreate an old cache file to test automatic cleanup:

touch -d '2 days ago' "$HOME/linux-lab/cache/expired.tmp"

Wait until the next minute boundary, then inspect recent log entries:

tail -n 5 "$HOME/linux-lab/logs/cleanup.log"

You may see something like:

[2026-11-12T15:05:01+08:00] Checking /home/ubuntu/linux-lab/cache
/home/ubuntu/linux-lab/cache/expired.tmp
[2026-11-12T15:06:01+08:00] Checking /home/ubuntu/linux-lab/cache

These are example logs; actual timestamps follow the server. The path after the first check shows a matching file was found. The next minute has only a check entry because no matching files remain. Checking alone shows that execution reached that step; it does not prove successful cleanup.

Finally inspect the files again:

ls "$HOME/linux-lab/cache"

Expect only:

recent.tmp

You have verified both that cron ran the script, through its logs, and that the old cache was removed, through the directory contents.

Change the test task to run daily

After successful verification, run:

VISUAL=vim EDITOR=vim crontab -e

Change the task's initial * * * * * to 15 3 * * *. The complete rule is:

15 3 * * * /bin/bash "$HOME/linux-lab/bin/purge-cache.sh" >> "$HOME/linux-lab/logs/cleanup.log" 2>&1

It now runs daily at 03:15 in server time. Confirm the saved change with crontab -l. If you only wanted to finish the exercise, edit the crontab and remove this task instead.


❓ Knowledge check

Q1: Why does a script work manually but fail under cron?

First inspect errors in cleanup.log, verify the task's user, and check the script path. cron's environment differs from an interactive terminal; do not assume the same environment variables or working directory.

Q2: Why does the log show a check time but no deleted files?

There may be no old .tmp files matching the conditions. Checking records a check; a file path appears only when a match is found. Inspect the final contents with ls.


🧪 Exercise

Change the cleanup threshold from approximately 1 day to approximately 3 days:

  1. Update the script's -mmin condition and save.
  2. Create .tmp files in the practice cache directory with modification times of 2 days ago and 4 days ago.
  3. Preview the selection with find ... -print, then temporarily schedule the task every minute.
  4. Inspect logs and files to confirm that only the 4-day-old file is deleted. Restore the daily schedule or remove the task afterward.

Hint: One day is 1440 minutes; three days are 4320 minutes.


🎉 You can now schedule Linux tasks with cron and verify automatic cleanup using both logs and file results!