How to clean up the /tmp folder contents on Linux servers

Each Linux server has a diretcory named /tmp which is installed with individual file system. it is used to hold temporary files. /tmp directory have all the all the website session files which is hosted on serve.

so if we removed those file incorrectly the user session got disconnected who is currently using database. Some times the /tmp directory got full, so you can’t write anything to mysql database and you start getting error messages. To resolve this you have to remove some content/files from /tmp directory to free space.

First of all you can check /tmp directory to find out what kind of files stored there.

root@server [/tmp]# ls -lh
total 50M
drwxrwxrwt 15 root root 508K May 6 13:26 ./
drwxr-xr-x 29 root root 4.0K May 3 03:32 ../
-rw------- 1 cppl cppl 1.8K 19 Sep 6 05:48 sess_01677a0944c23187135748f09037f13a
-rw------- 1 cppl cppl 19 Sep 6 13:22 sess_0292d1af394d15f09e5565af76304acd

In my server /tmp folder have only session file, so i’m going to remove only session files.

Shell script to clean session files:

For this purpose we can use the simple shell script and assign to cron once in a day.

#!/bin/bash

rm -rf /tmp/sess_*
/sbin/service mysql restart

Just create the shell file called tmpclean.sh at /etc/cron.daily folder and put the above codes. It will clean the session files once in a day and restart the mysql service.
Make sure your shell file have executable permissions (755).

Clean /tmp folder without affecting anything ?

Many script creates session files after every seconds. You can use mtime argument with the find command to search out little bit old files say 1 hour older. So if you remove them it doesn’t effect much to your websites.

#!/bin/bash

find /tmp/sess_* -mtime +1h -exec rm {} \;

Just create the shell file called tmpclean.sh at /etc/cron.hourly folder and put the above codes. It will clean the session files every one hour. Make sure your shell file should have executeable permission (755).

That’s all we have to do clean up the /tmp folder contents in Linux servers  Please give your opinion below if you experience any issues or to discuss your ideas and experiences.