I have a script with a hard-coded bash array of mysql connection variables. The script right now is basically like this:
declare -a dbarr=($devdb1 $devdb2)
for db in "${dbarr[@]}"; do
mysql $db -NBe "show variables like 'key_buffer_size';"
done
This works without any problems.
However, I would like to instead move these into a file instead of hard-coding them (there are several hundred), like:
dev|$devdb1
dev|$devdb2
tst|$tstdb1
..
each variable in the above list resolves to a parameter like:
--defaults-extra-file=/home/mysql/env/devserver.devdb1
--defaults-extra-file=/home/mysql/env/devserver.devdb2
--defaults-extra-file=/home/mysql/env/testserver.tstdb1
You can then simply connect to mysql like:
mysql $devdb1
if I read these in (via readarray or a while loop), the only way I can get this to work is to use eval
envfile="/home/mysql/env/envfile"
readarray -t envarr < <(gawk -F'|' '/^dev/{print $2}' "${_envfile}")
for db in "${envarr[@]}"; do
eval "connstr=$db"
mysql $connstr -NBe "show variables like 'key_buffer_size';"
done
Without the eval, it fails with:
+ mysql '$devdb1' -NBe 'show variables like '\''key_buffer_size'\'';'
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
+ mysql '$devdb2' -NBe 'show variables like '\''key_buffer_size'\'';'
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
The only way I have found to have the $devdb1, etc. "resolved" is with eval - which I understand the dangers of - but I have not found any other way.
I tried using ${!db} instead of the eval above, but it returns nothing.