Executing Dynamically Generated SQL Queries in a Shell Script and Saving the Output to a Variable

If you would like to, in a shell script, dynamically generate SQL queries for MySQL and save the output of those queries to a variable that you can then use in the script, here is an example:

#!/bin/bash

for i in `cat tables_list.txt`
do

   # Build the query
   QUERY="SELECT count(*) FROM ${i}"

   # Run the query from the command-line and save the
   # output into the $ROW_COUNT variable
   ROW_COUNT=$(echo $QUERY | mysql -u${USER_NAME} -p${PASSWORD} -h ${HOST} -P ${PORT} --skip-column-names ${DBASE})

   # Do something with the var...
   echo -n -e "$ROW_COUNT\t" >> $OUT_FILE
   echo "$i" >> $OUT_FILE

done;

Leave a Reply