Simulate reboot to clear tmp on the Windows Linux subsystem

Solution 1:

FSTAB - Doesn't work as expected on WSL1, but may work correctly on WSL2

The best approach is to make sure your /tmp directory is a temporary mount, but this doesn't work as expected on WSL.

Edit your /etc/fstab file (with admin permissions, i.e. sudo vi /etc/fstab)

Add the following line

tmpfs   /tmp    tmpfs   noexec,defaults,nodev,nosuid,noatime,size=256m  0 0

Now close all bash terminals and re-open.

On closer inspection for WSL1, this seems to be creating a new /tmp mount for each bash terminal, hence does not work as expected. Specifically, opening a new WSL1 terminal after another has already been established orphans the original /tmp mount (with it still taking up space) and then creates a new one. Earlier WSL1 terminals seem to point to the new /tmp mount, and lose anything saved in the /tmp mount prior to the new WSL1 terminal opening.

Mount in .bashrc - Recommended for WSL1

The recommended suggestion is to mount in the ~/.bashrc if not already mounted. This seems to work for me

mount|grep -E "^[^ ]* on /tmp " >/dev/null
if [ "$?" != "0" ];then
        echo "Mounting tmp"
        sudo mount -t tmpfs tmpfs /tmp -o noexec,defaults,nodev,nosuid,noatime,size=256m
fi

Solution 2:

Use tmpreaper - it is a tool designed exactly for regular cleaning of /tmp of unused files. In many Linux distros it is installed by default.

At installation a cron job should automatically be set up to run tmpreaper every day. By default, it removes files and subdirectories that haven't been used for 7 days, except for several "protected" names like for example /tmp/lost+found. You can change this value in /etc/tmpreaper.conf config file.