Rodolfo Bandeira

Rodolfo Bandeira

software, electronics, security, devops, thoughts

How to use crontab in CentOS Linux

If you want to automate tasks in CentOS, you must to edit /etc/crontab like the user you want to run your application.

Let’s see what we have in default /etc/crontab:

sudo cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
HOME=/
# 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 
#
#For instance, if you want to run a mysql.sh file every day, justĀ use this:
# This like executes mysql.sh every 12:45pm, 6:45pm, 2:45am every 
45 12,18,02 * * * /root/mysql.sh

This is mysql.sh file:

[root@srvcob ~]# cat mysql.sh
#!/bin/bash
# Simple script to backup MySQL databases

# Parent backup directory
backup_parent_dir="/var/backups/mysql"

# MySQL settings
mysql_user="USER"
mysql_password="PASSWORD"
mysql_host="HOSTNAME"

# Read MySQL password from stdin if empty
if [ -z "${mysql_password}" ]; then
 echo -n "Enter MySQL ${mysql_user} password: "
 read -s mysql_password
 echo
fi

# Check MySQL password
echo exit | mysql -h ${mysql_host} --user=${mysql_user} --password=${mysql_password} -B 2>/dev/null
if [ "$?" -gt 0 ]; then
 echo "MySQL ${mysql_user} password incorrect"
 exit 1
else
 echo "MySQL ${mysql_user} password correct."
fi

# Create backup directory and set permissions
backup_date=`date +%Y_%m_%d_%H_%M`
backup_dir="${backup_parent_dir}/${backup_date}"
echo "Backup directory: ${backup_dir}"
mkdir -p "${backup_dir}"
chmod 700 "${backup_dir}"

# Get MySQL databases
mysql_databases=`echo 'show databases' | mysql -h ${mysql_host} --user=${mysql_user} --password=${mysql_password} -B | sed /^Database$/d`

# Backup and compress each database
for database in $mysql_databases
do
 if [ "${database}" == "information_schema" ] || [ "${database}" == "performance_schema" ]; then
 additional_mysqldump_params="--skip-lock-tables"
 else
 additional_mysqldump_params=""
 fi
 echo "Creating backup of \"${database}\" database"
 mysqldump ${additional_mysqldump_params} -h ${mysql_host} --user=${mysql_user} --password=${mysql_password} ${database} | gzip > "${backup_dir}/${database}.gz"
 chmod 600 "${backup_dir}/${database}.gz"
done
[root@srvcob ~]#

Rodolfo

Last modified:


Share:
LinkedIn
WhatsApp