Mencari Sesuatu ?

Jumat, 29 Juli 2022

BASH : MYSQL menghapus tables tertentu yang sudah berumur lebih dari berapa periode, contoh 6 bulan 2 bulan 3 bulan 1 bulan, 2 minggu dll

BASH : Maintenance database mysql, menghapus tables tertentu yang sudah berumur lebih dari berapa periode, contoh 6 bulan 2 bulan 3 bulan 1 bulan, 2 minggu dll
#!/usr/bin/env bash
####!/bin/sh
#set -x  

#MYSQL INFO
#change it
SQLUSER="username"
#change it
SQLPASS="password"
#change it
DB="database_name" 
DATE=`date +'%Y-%m-%d'`

#Param Info 
DAYS="6 MONTH"
#Temp name for tables
TMPFILE="/tmp/tables_list-$DATE" 
 
export MYSQL_PWD=$SQLPASS
CMD="mysql -u$SQLUSER --skip-column-names -s -e" 
echo "IT WILL DELETE tables from $DB older then $DAYS"

echo "Script Started @ $DATE "
#change the table_prefix to delete certain table only
$CMD "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '$DB' AND (table_name LIKE '%tbl_prefix_1_%' or table_name LIKE '%tbl_prefix_1_%') AND create_time < NOW() - INTERVAL $DAYS;" | awk '{print $1}' > $TMPFILE
num=0
cat $TMPFILE | while read tables
do
num=$[$num+1]
TABLE_TO_DELETE=`echo $tables`
$CMD "use $DB; DROP TABLE \`$TABLE_TO_DELETE\`;"
#$CMD "use $DB; select count(*) FROM \`$TABLE_TO_DELETE\`;"
DATE=`date +'%Y-%m-%d'`
echo "$DB_TRIMMING deleting TABLE $TABLE_TO_DELETE FROM $DB " 
done
echo "Script ended @ $DATE "

Based on code from : https://aacable.wordpress.com/2021/07/29/mysql-delete-single-table-older-than-x-days-using-script/

Tidak ada komentar:

Posting Komentar