Commands.page Logo

How to Create Temp Directory Auto-Delete on Ubuntu Reboot

This article details the process of setting up a custom temporary directory in Ubuntu that automatically purges its contents during system startup. You will learn how to utilize systemd-tmpfiles to define cleanup rules, ensuring reliable management of temporary data without manual intervention or complex scripts.

Use Built-in Temporary Locations

The simplest method is to use the existing /tmp or /run directories. Both locations are cleared automatically every time the system boots. If your application allows it, store temporary files directly in /tmp to leverage this built-in behavior without additional configuration.

Create a Custom Temporary Directory

If you require a specific path, such as /var/myapp/temp, you must configure systemd to manage it. Ubuntu uses systemd-tmpfiles to handle the creation and cleaning of temporary directories.

1. Create a Configuration File

Create a new configuration file in the /etc/tmpfiles.d/ directory. This tells systemd how to handle your specific folder. Replace myapp with your desired service name.

sudo nano /etc/tmpfiles.d/myapp.conf

2. Define the Cleanup Rule

Add the following line to the file. This command specifies that the directory should be created with specific permissions and removed during boot.

d /var/myapp/temp 0755 root root -

For a strict reboot-only wipe of content, use the L or d type combined with systemd boot services. However, the most reliable method for a full wipe on boot is to mount a tmpfs or rely on the systemd-tmpfiles-clean.service which runs at boot.

To ensure the directory is emptied on boot, add this line instead:

D /var/myapp/temp 0755 root root -

The capital D argument creates the directory and removes its contents if it already exists when the systemd-tmpfiles-setup service runs during boot.

3. Apply the Configuration

Create the directory immediately and test the configuration without rebooting by running:

sudo systemd-tmpfiles --create /etc/tmpfiles.d/myapp.conf

4. Verify the Setup

Reboot your system to confirm the behavior.

sudo reboot

After the system restarts, check the directory. It should exist but be empty.

ls -la /var/myapp/temp

Any files created before the reboot will be gone, ensuring a clean state for your applications.