Skip to content

Instantly share code, notes, and snippets.

@JustinMcNamara74
Last active August 29, 2015 14:16
Show Gist options
  • Save JustinMcNamara74/1824fc2e75baf23f78f3 to your computer and use it in GitHub Desktop.
Save JustinMcNamara74/1824fc2e75baf23f78f3 to your computer and use it in GitHub Desktop.
#BASH Extract a list of tables from a MySQL database.
#!/bin/bash
PATH=/usr/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/youruser/bin
DB=db
USER=usr
PASS=pw
PATHTO=/path/to/
DIR=extract$(date +%Y%m%d)
#Declare an array of tables
declare TABLE_LIST=("tableA" "tableB" "tableC")
#If the destination path doesn't exists, create it
if [ ! -d $PATHTO/$DIR ]; then
mkdir -p $PATHTO/$DIR
echo "created $DIR#2"
fi
#For each table in the array, extract the data into a .csv file (delimited by "|"), to the destination location
for table in "${TABLE_LIST[@]}"; do
tableName=${table//_/}
echo "extracting $tableName.."
mysql -u $USER -p$PASS $DB -e "Select * from $table" | sed 's/\t/"|"/g' > $PATHTO/$DIR/${DB}_${tableName}_$(date +%Y%m%d).csv
echo "extract completed"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment