Add cron jobs to delete logs periodically

From Wikipedia:

cron is the time-based job scheduler in Unix-like computer operating systems. cron enables users to schedule jobs (commands or shell scripts) to run periodically at certain times or dates. It is commonly used to automate system maintenance or administration.

The final cron job script is here https://gist.github.com/c487d6d8b2b52219a87b

sudo crontab –e
2 0 * * * /opt/tools/delete_old_logs.sh /var/log >> /var/log/cron_job.log 2>&1

Crontab format

The basic format for a crontab is:

minute hour day_of_month month day_of_week command [args]
  • 1: minute (0-59)
  • 2: hour (0-23)
  • 3: day_of_month (0-31)
  • 4: month (0-12 [12 == December])
  • 5: day_of_week Day of the week(0-7 [7 or 0 == sunday])
  • /path/to/command – Script or command name to schedule

Easy to remember format:

* * * * * command to be executed
- - - - -
| | | | |
| | | | ----- Day of week (0 - 7) (Sunday=0 or 7)
| | | ------- Month (1 - 12)
| | --------- Day of month (1 - 31)
| ----------- Hour (0 - 23)
------------- Minute (0 - 59)

Multiple times may be specified with a comma(,), a range can be given with a hyphen(-), and the asterisk symbol(*) is a wildcard character. Spaces are used to separate fields. For example, the line:

*/5 9-16 * 1-5,9-12 1-5 ~/bin/i_love_cron.sh

Will execute the script i_love_cron.sh at five minute intervals from 9 AM to 4:55 PM on weekdays except during the summer months (June, July, and August). More examples and advanced configuration techniques can be found below.

Basic commands for cron management

Crontabs should never be edited directly; instead, users should use the [crontab][1] program to work with their crontabs. To be granted access to this command, user must be a member of the users group (see the gpasswd command).

To edit their crontabs, they may use:

$ crontab -e

Note: By default the crontab command uses the vi editor. To change it, export EDITOR or VISUAL, or specify the editor directly: EDITOR=vim crontab -e.

To view their crontabs, users should issue the command:

$ crontab -l

To remove their crontabs, they should use:

$ crontab -r

Remove or delete single cron job using command

crontab -l | grep -v '/var/crontab/xxx.sh' | crontab -

crontab -l lists the current crontab jobs

grep -v filter some line

crontab - adds all the printed stuff into the crontab file.

Related Articles