Pages

Tuesday, January 16, 2018

Using cron to schedule scripts accessing the target files via relative paths. Disabling emails with the cron output

It is another note for myself. Under Linux task execution is easy to schedule with cron service. The service can execute script as the indicated user. crond service reads /etc/crontab: once a minute. If crontab file has been modified, cron service does not need to be restarted. Any output from the executed script is mailed to user, e.g. root, whose name is assigned to MAILTO environment variable in the crontab. If the recipient is not you but your admin, he might not be happy with lot of spam. To disable repetitive emails with the output of executed jobs add

&> /dev/null
to the end of the each scheduled command.

A sample /etc/crontab:

SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
MYDIR="/data/apache-tomcat-8.5.13/bin"

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
1  23  *  *  *  test  $MYDIR/clearLogs.sh &> /dev/null
Script deleting outdated files

For example, a script that copies MySQL contents and deletes the backups older than 3 days:

#!/bin/bash

MYSQL_DIR=/data/mysql
BACKUP_DIR=/data/mysqlDailyBackup
service mysqld stop
cp -r $MYSQL_DIR $BACKUP_DIR/mysql_`date +"%d-%m-%Y"`
service mysqld start
service httpd restart
find $BACKUP_DIR  -maxdepth 1 -mindepth 1 -type d -mtime 3 -exec rm -rf {} \;

Suppose, to be more portable, a script to be executed refers to the target files in some nested or sibling folders only via relative paths so that if the file path of the scheduled script changes nothing except the invoking line in the crontab has to be adjusted.

For example, the scheduled script is located in Tomcat bin folder and it simply deletes the outdated log files in Tomcat log folder. If the Tomcat is moved to some other location, to ensure that the automatic task is successfully executed, you one needs to adjust only the path to the script in crontab file, and nothing inside the script itself.

The parent folder path can be determined with a command:

script_parent_folder_path=$(dirname "$0")

A sample scheduled script deleting Tomcat log files that are older than one day:

#!/bin/bash
script_parent_folder_path =$(dirname "$0")
find $ script_parent_folder_path/../logs/ \( -name "*.log" -or -name "*.txt" \) -type f -mtime +1 -exec rm -f {} \;
Cron log

One can see the cron log in /var/log/cron.

No comments:

Post a Comment