Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save rbhushan90/bbfe5551295c51335bb1e8c8e4a500d3 to your computer and use it in GitHub Desktop.
Save rbhushan90/bbfe5551295c51335bb1e8c8e4a500d3 to your computer and use it in GitHub Desktop.
DBNAME=<database_name>
TABLE=<table_name>
FNAME=/path/to/output/dir/$(date +%Y.%m.%d)-$DBNAME.csv
#(1)creates empty file and sets up column names using the information_schema
mysql -u <username> -p<password> $DBNAME -B -e "SELECT COLUMN_NAME FROM information_schema.COLUMNS C WHERE table_name = '$TABLE';" | awk '{print $1}' | grep -iv ^COLUMN_NAME$ | sed 's/^/"/g;s/$/"/g' | tr '\n' ',' > $FNAME
#(2)appends newline to mark beginning of data vs. column titles
echo "" >> $FNAME
#(3)dumps data from DB into /var/mysql/tempfile.csv
mysql -u <username> -p<password> $DBNAME -B -e "SELECT * INTO OUTFILE '/var/mysql/tempfile.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' FROM $TABLE;"
#(4)merges data file and file w/ column names
cat /var/mysql/tempfile.csv >> $FNAME
#(5)deletes tempfile
rm -rf /var/mysql/tempfile.csv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment