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
Lets create directory where we will store our script file.
$ cd ~/ $ mkdir script
Create new shell script file and make it executable:
$ cd script $ touch delete_logs.sh $ chmod +x delete_logs.sh
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.
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.
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).
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
0 0 * * 0 /bin/sh /root/script/delete_logs.sh
Save and close.
Now cronjob will execute delete_logs.sh script every week:
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 coffee