How to clean temporary files in server automatically

You might have seen that the temporary files in server increases in size gradually with use. It can ultimately lead to space consumption issue in server. You can delete the temporary files manually from terminal. However for busy websites and servers, manual deletion of temporary files is not an optimum solution. Automatic deletion can be achieved by using crontab for the servers.

In order to delete the temporary files, please find the temporary files folder in your server. The folder may be in /tmp/ or /var/tmp/ or anywhere else depending on the operating system distro. I am using ubuntu server for this example and the temporary files are available in /tmp/ folder. Try deleting the files manually from terminal with the following command:

sudo rm -r /tmp/*

This will delete the files from the temporary folder and free up your valuable server disk space. However some servers' need a restart after cleaning temporary files which we will address in our crontab job now.

Automatic cleaning of temporary files:

In order to clean and restart server automatically, please create a cron job from sudo user as it needs super user permissions. Type the following command in terminal.

sudo crontab -e

The crontab will be opened up for editing. If you're using it for first time, it will ask you to choose an editor for editing crontab. You can choose any one. I generally use nano. Enter the following details for deleting the temporary files close to midnight (You can choose your time accordingly in crontab):

57 23 rm -r /tmp/ 59 23 * /sbin/shutdown -r now

Save the above in nano using Ctrl+O and exit using Ctrl+X.

Congratulations! You have set up your crontab for automatic cleaning for temporary files in server. You can check the crontab listing any using the following command:

sudo crontab -l

Thank you for reading. You may share this article, if you find it useful.