Table of Contents
In this article I will show very basic shell Script to Delete Log Files in Linux and schedule logs deletion using a cron job.
Linux Log Files
The Linux operating system and running applications constantly generate various types of messages that are logged in various log files.
Most of the log files are contained in the /var/log directory.
[root@kms log]# du -sh /var/log 30GB /var/log
Script to delete a log file in Linux
1. Create a directory where we will store our script file.
cd /usr mkdir script
2. Create new shell script file and make it executable:
cd script touch delete_logs.sh chmod +x delete_logs.sh
3. In this case we need delete this log /var/log/vlmcsd.log
4. 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/vlmcsd.log
Then save and close.
4. Now we need create cronjob for execute our delete_logs.sh script.
To edit crontab file, let’s run the following command:
sudo crontab -e
Add the following line into the crontab file to delete the log file every week automatically.
0 0 * * 0 /bin/sh /usr/script/delete_logs.sh
Save and close crontab. Now cronjob will execute delete_logs.sh script every week.
More schedules option:
- every 5th minute: */5 * * * *
- every 15th minute: */15 * * * *
- every 60th minute: 0 * * * *
Each line of a crontab file represents a job, and looks like this:
# ┌───────────── minute (0 - 59) # │ ┌───────────── hour (0 - 23) # │ │ ┌───────────── day of the month (1 - 31) # │ │ │ ┌───────────── month (1 - 12) # │ │ │ │ ┌───────────── day of the week (0 - 6) (Sunday to Saturday; # │ │ │ │ │ 7 is also Sunday on some systems) # │ │ │ │ │ # │ │ │ │ │ # * * * * * <command to execute>
You can use quick and simple editor for editing cron schedule expressions.
Delete multiple log files in Linux
In some cases, you want to delete all vls_proxy1.log, vls_proxy2.log, vls_proxy3.log…, log files, so you have selected only these files: *proxy*.log.
Edit the delete_logs.sh with the asterisk in the log files name.
# Linux script to delete Log files weekly #!/bin/sh sudo rm -rf /var/log/*proxy*.log
Hope this post help you learned how to write basic Linux shell script for delete Log files. And make it executable.