2

I'm using Ubuntu 22.04LTS. I would like to create a folder "temp" where during my session I save the files that are, as the name suggest, temporary. How can I define a scritp that at shutdown automatically deletes the contents of this folder?

Ex: I download few documents that I need for some tasks but at the end of the day I don't need to keep them, thus avoiding to accumulate useless files.

Iano
  • 23
  • 4
    There is already a place for that called /tmp/ ... Put your stuff there and they will be cleaned on reboot. – Raffa Feb 14 '24 at 11:26
  • 3
  • @Raffa and don't use snaps in that case? I know most can't write to /tmp (but don't tell you, they just fail silently) which is why I avoid them all - so I can't test. Firefox installs as a snap in 22.04 even if you'd previously installed a fully functioning version, so anyone on a default setup could check easily. – Chris H Feb 14 '24 at 20:36
  • @ChrisH That is indeed a bit tricky ... The snap service itself does access /tmp and create /tmp/snap-private-tmp but, restricts sharing files between applications in it ... However, the snap applications should be able to access /tmp (on their own) normally unless /tmp is a VFS mount (tmpfs and external media mounts included) and the latter could be solved by granting the snap application needed permission or by a bind mount of /tmp in the user's home like mount --bind /tmp/ /home/user/tmp/ ... Take that with a grain of salt though "oh snap :-)". – Raffa Feb 15 '24 at 06:37
  • @Raffa All I know is it's easier to install proper executables that work properly than mess about with working round snaps. I'm not interested in troubleshooting. I've stopped using Ubuntu for clean installs because of them (it's the silent refusal to do what they're told - really bad practice, worse the MS patronising error messages - that stopped me), and may do a clean install of Debian rather than upgrading a system, after the hassle with the anti-user behaviour around Firefox (deleting the PPA for the real installer, installing a snap, for lots of the stuff in my profile to not work) – Chris H Feb 16 '24 at 14:12

3 Answers3

4

Alternative 01: (See alternative 02 or @Raffa's comment for shortcoming of alternative 01.)

Lets create our temporary directory, and own it as normal user so that we can write to it as normal user:

sudo mkdir /my_temp_files/
sudo chown $USER:$USER /my_temp_files/

Lets write a script to remove the temporary files at system startup. We will store the script in the following directory:

sudo mkdir -p /opt/remove_my_temp_files/bin/

Create a file named remove_my_temp_files.sh as:

sudo touch /opt/remove_my_temp_files/bin/remove_my_temp_files.sh
sudo chmod 755 /opt/remove_my_temp_files/bin/remove_my_temp_files.sh
sudo chown root:root /opt/remove_my_temp_files/bin/remove_my_temp_files.sh

Write the folling to this file:

#!/bin/bash

if [[ -d /my_temp_files ]] ; then rm -fr /my_temp_files/* rm -fr /my_temp_files/.* fi

Now, create a file named remove_my_temp_files.service as:

sudo touch /etc/systemd/system/remove_my_temp_files.service
sudo chmod 644 /etc/systemd/system/remove_my_temp_files.service
sudo chown root:root /etc/systemd/system/remove_my_temp_files.service

And write the following to this file:

[Unit]
Description=Removes My Temporary Files.

[Service] Type=oneshot ExecStart=-/bin/bash -c '/opt/remove_my_temp_files/bin/remove_my_temp_files.sh'

[Install] WantedBy=multi-user.target

Now, finally enable remove_my_temp_files.service as:

sudo systemctl enable remove_my_temp_files.service

Now, files and directories created within this /my_temp_files/ directory will be deleted on every system startup.

Alternative 02:

As @Raffa suggests in his comments below, my way of rm /path/to/dir/* is limited by the permitted size of command line, and using system service is bit too much for a task that can be simply accomplished by crontab as he suggests, here is the alternative answer:

Write the following code in $HOME/bin/remove_user_temp.sh :

#!/bin/bash

declare MY_TEMP_DIR="$HOME/my_temp_dir/"

if [[ -e "$MY_TEMP_DIR" ]] ; then rm -rf "$MY_TEMP_DIR" if [[ ! -e "$MY_TEMP_DIR" ]] ; then mkdir "$MY_TEMP_DIR" fi fi

Make this script executable:

chmod +x $HOME/bin/remove_user_temp.sh

Edit the crontab with:

crontab -e

Choose the file editor of your choice, if permitted, then begin with editing the cron job. At the end of the file, add:

@reboot $HOME/bin/remove_user_temp.sh

Save your edit, and exit crontab. This will also delete the files in your temporary directory at system reboot.

Alternative 03:

Easiest alternative is to put your temporary files in /tmp/ or /dev/shm/ directory. The files stored in /tmp will get deleted next time your system boots up, while those in /dev/shm are stored in computer's memory (rather than on the disk) and will be deleted when the computer shuts down or goes to reboot.

rusty
  • 16,327
  • There already exists a /tmp/ folder and a systemd service to delete its contents periodically. See this answer to the older question linked above. – user68186 Feb 14 '24 at 15:55
  • 1
    rusty (if it must be) 1) The shell glob * will not expand to hidden files and directories starting with a dot . without setting shopt -s dotglob 2) If the glob expands to arguments to rm that exceed the maximum arguments limit by the OS, then that will fail with an error without removing anything … You can use find /dir -delete to solve both … Also a system service might be an overkill and @reboot … user cron job or even a shell command string as a user startup application will do … Also it’s better and easier to keep user directories in their home I think. – Raffa Feb 14 '24 at 15:59
  • … also it might be faster to just remove the directory itself and then create it simply like rm -r /home/user/dir; mkdir /home/user/dir – Raffa Feb 14 '24 at 16:31
  • 1
    @Raffa, thanks for pointing out the limit on size of command line. Never before used @reboot in my crontab before. Edited my answer to include your suggests. – rusty Feb 14 '24 at 17:31
3

There is a way built into Linux, called tmpfs, that can achieve exactly this. To use it, make a folder tmpfs, and everything inside the folder after you made it tmpfs will evaporate when it is no longer tmpfs or when the computer shuts down. The downsides are that files in tmpfs folders can only reside in RAM or swap.

# mount -t tmpfs tmpfs temp

The filesystem don't store if a folder is tmpfs. To permanently mark a folder as tmpfs, you should edit /etc/fstab:

tmpfs   /tmp    tmpfs   defaults        0       2

In addition to tmpfs, Ubuntu's services autoclean the /tmp directory on startup (thanks raj), so you can place any temporary files there.

mcendu
  • 307
  • 4
    No, /tmp in Ubuntu is not tmpfs, it is just a regular directory under the root filesystem that is automatically cleaned on reboot by startup scripts. – raj Feb 14 '24 at 15:07
  • 1
    @raj if OP makes the changes in fstab as mcendu states, then it'll be replaced with a tmpfs environment - otherwise you're right. (my /tmp/ is set up this way and the scripts still work to 'clean" the already empty environment because it's a tmpfs on my system at boot) – Thomas Ward Feb 14 '24 at 15:59
  • @raj are you sure? All the Ubuntu systems I have access to have a tmpfs system at /tmp. These are all Server installs though. Are you saying that on your system, df /tmp doesn't show that it's a tmpfs? – terdon Feb 14 '24 at 19:03
  • @terdon Yes, I am sure. On my system (20.04) tmpfs are: /run, /sys/fs/cgroup and /dev/shm. I also checked on a very old 10.04 system that I use at work for some purposes and it's similar. I've never seen /tmp being tmpfs on a desktop Ubuntu system (unless of course someone manually configured it that way). – raj Feb 14 '24 at 21:48
  • 1
    @terdon Ubuntu is unusual in that it is inconsistent in how it handles /tmp based on the install type. Server installs do indeed use tmpfs there. Desktop installs do not, likely because they assume users will be stupid and put lots of big files there. – Austin Hemmelgarn Feb 15 '24 at 03:03
  • @AustinHemmelgarn Could not reproduce on a fresh Ubuntu 22.04 server VM – Daniel T Feb 29 '24 at 13:07
0

Here is a much simpler version of @rusty's answer. I will use the official systemd-tmpfiles mechanism. Note that just like that answer, my answer removes things at power on not power off. Just paste the following into /etc/tmpfiles.d/my-temp-files-1503475-1004020.conf :

D /my_temp_dir 0755 root root

Change root to $USER if necessary. For the user-only alternative, you can use ~/.config/user-tmpfiles.d/ after systemctl --user enable systemd-tmpfiles-setup. This uses systemd-tmpfiles like @muru's answer but it uses systemd-tmpfiles-setup not systemd-tmpfiles-clean. There is no need to use a mix of bash scripts in /opt, enableing and installing .services, manual rm, chmod, chown, /opt, or cron for such a basic task.

Daniel T
  • 4,594