Skip to content

Instantly share code, notes, and snippets.

@krisanalfa
Created January 20, 2014 05:24
Show Gist options
  • Save krisanalfa/8515274 to your computer and use it in GitHub Desktop.
Save krisanalfa/8515274 to your computer and use it in GitHub Desktop.
Do any what you wanna do with your MySQL table with an iteration
#!/usr/bin/env bash
# Run this script with: bash magic_table_script.sh myDatabaseName
# Or you can work with multiple database by typing: bash magic_table_script.sh myDatabaseName,anotherDatabaseName,yetAnother
# I use root account for do this magic, so you could provide your root password below
# Change your database password here
mysqlRootPassword="my_S3cr3+_pa^^w012D"
function doWhatYouWannaDo() {
# Usage: doWhatYouWannaDo $dbname
dbname=$1;
sql="select TABLE_NAME from TABLES where TABLE_SCHEMA='$dbname' and TABLE_TYPE = 'BASE TABLE'";
declare -a tableName=($(mysql -u root -p"`echo $mysqlRootPassword`" -e "use information_schema; `echo $sql`" | awk '{print $1}' | sed 's/TABLE_NAME//g' | sed ':a;N;$!ba;s/\n/ /g'));
arrayLength=$(echo ${#tableName[@]});
for (( i = 0; i < $arrayLength; i++ )); do
echo "Working in database $dbname for table ${tableName[i]}";
# For example if you want to convert your WHOLE table charset into utf8 and collation to utf8_general_ci
mysql -u root -p"$mysqlRootPassword" -e "USE $dbname; ALTER TABLE ${tableName[i]} CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;"
# For example if you want to alter your WHOLE table to InnoDB Engine
mysql -u root -p"$mysqlRootPassword" -e "USE $dbname; ALTER TABLE ${tableName[i]} ENGINE='InnoDB';"
done
echo "Done for $dbname";
}
# Declare the array
IFS=',' read -a array <<< "$1"
# Execute Looping
for index in "${!array[@]}"
do
doWhatYouWannaDo "${array[index]}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment