Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AdnaneX/edb4b277204fb701de38e58e77f99856 to your computer and use it in GitHub Desktop.
Save AdnaneX/edb4b277204fb701de38e58e77f99856 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
@afanasy
Copy link

afanasy commented Oct 2, 2022

How about

mysql -sN -e "select group_concat(column_name order by ordinal_position) name from information_schema.columns where table_schema = '$DBNAME' and table_name = '$TABLE'"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment