forked from uberhacker/shrink-ibdata1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shrink
executable file
·70 lines (70 loc) · 1.93 KB
/
shrink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#!/bin/bash
cd
MYSQL_USER=root
MYSQL_PASS=root
MYSQL=$(which mysql)
if [ $? == 1 ]; then
echo "MySQL is not installed."
exit 1
fi
if test $1; then
if [[ "$1" != "-k" ]]; then
echo "Invalid switch $1."
echo "Usage: $0 [-k]"
echo "Use the -k switch to keep backups instead of restoring the databases"
exit 1
fi
fi
MYSQLD=$(pidof mysqld)
if [ -z "$MYSQLD" ]; then
sudo service mysql start
fi
DBS=$($MYSQL -u$MYSQL_USER -p$MYSQL_PASS -e 'show databases' | awk '{print $1}' | grep -v '^Database')
SAVE_DBS="information_schema mysql performance_schema"
SIZE_BEFORE=$(df -P . | awk 'NR==2 {print $4}')
if [[ "$DBS" != "$SAVE_DBS" ]]; then
for DB in $DBS; do
DROP=1
for SAVE_DB in $SAVE_DBS; do
if [ $SAVE_DB == $DB ]; then
DROP=0
break
fi
done
if [ $DROP == 1 ]; then
echo "Dumping $DB database..."
mysqldump -u$MYSQL_USER -p$MYSQL_PASS $DB | gzip > $DB.sql.gz
if [ -f $DB.sql.gz ]; then
echo "Database $DB backed up successfully."
echo "Dropping $DB database..."
$MYSQL -u$MYSQL_USER -p$MYSQL_PASS -e "drop database $DB"
else
echo "Backup of database $DB failed."
fi
fi
done
fi
sudo service mysql stop
sudo rm -f /var/lib/mysql/ib*
sudo service mysql start
if ! test $1; then
if [[ "$DBS" != "$SAVE_DBS" ]]; then
for DB in $DBS; do
if [ -f $DB.sql.gz ]; then
echo "Restoring database $DB..."
gunzip $DB.sql.gz
$MYSQL -u$MYSQL_USER -p$MYSQL_PASS -e "create database if not exists $DB"
$MYSQL -u$MYSQL_USER -p$MYSQL_PASS $DB < $DB.sql
if [ $? == 0 ]; then
echo "Database $DB restored successfully."
rm -f $DB.sql
else
echo "Restore of database $DB failed."
fi
fi
done
fi
fi
SIZE_AFTER=$(df -P . | awk 'NR==2 {print $4}')
SIZE_SAVED=$(($SIZE_AFTER-$SIZE_BEFORE))
echo "Shrunk /var/lib/mysql/ibdata1 and recovered $SIZE_SAVED kilobytes."