Script To Delete Log Files in Linux

In this article I will show very basic shell Script to Delete Log Files in Linux and schedule logs deletion using a cron.

Linux Log Files

The Linux operating system and running applications constantly generate various types of messages that are logged in various log files.
Logging is the main source of information about the operation of the system and its errors.
Most of the log files are contained in the /var/log directory.

Shell Script To Delete Log Files in Linux

Step 1

Lets create directory where we will store our script file.

$ cd ~/
$ mkdir script

Step 2

Create new shell script file and make it executable:

$ cd script
$ touch delete_logs.sh
$ chmod +x delete_logs.sh

Step 3

In my case I need delete all tx_proxy1.log, tx_proxy2.log, tx_proxy3.log…, log files, so I have selected only these files: *proxy*.log.

Linux log files

Edit the delete_logs.sh file with your favorite text editor and paste text below into that file:

# Linux script to delete Log files weekly

#!/bin/sh

sudo rm -rf /var/log/*proxy*.log

Then save an close.

Step 4

Now we need create cronjob for execute our delete_logs.sh script.
This cron job will executed once a week at 00:00 on Sunday (0 0 * * 0).

Or:

every 5th minute: */5 * * * *
every 15th minute: */15 * * * *
every 60th minute: 0 * * * *

BTW, you can use quick and simple editor for editing cron schedule expressions – crontab guru.

To edit crontab file run:

sudo crontab -e

Then paste:

0 0 * * 0 /bin/sh /root/script/delete_logs.sh

Save and close.

Now cronjob will execute delete_logs.sh script every week:

That’s it!

Conclusion

Yo just learned how to write basic Linux shell script for delete Log files. And make it executable.

Also how to run that script as a cron job.

Read also: Cron Job To Delete Files Older Than X Days.

   

If you like what you are reading, please:

Buy me a coffeeBuy me a coffee

arstech

Start the discussion at forum.arstech.net