I am in the process of writing a bash script to display various statistics, some of which come from a MySQL database. The pertinant code I'm having difficulty with is:
read min max rows <<< $(mysql $dbDatabase -u $dbUser -p$dbPass -B -N -e \
"SELECT MIN(\`DateTime\`), MAX(\`DateTime\`), COUNT(*) FROM $dbTable")
echo "Min Date:" $min
echo "Max Date:" $max
echo "Total Rows:" $rows
The result of its execution is:
Min Date: 2013-03-18
Max Date: 20:30:00
Total Rows: 2014-07-31 14:30:00 11225139
Which obviously is not what I intend (the DateTime value has been split)
According to Google, $IFS
should be the answer to my problem. Unfortunately, I'm still unsuccessful in parsing the results correctly.
IFS=$'\t' read min max rows <<< ...
The result is:
Min Date: 2013-03-18 20:30:00 2014-07-31 14:30:00 11225139
Max Date:
Total Rows:
I find this odd since msyql -B | tr $'\t' 'X'
proves visually that the fields are separated by tabs.
As a workaround, I can do something like the following to produce the desired output:
read min max rows <<< $(mysql $dbDatabase -u $dbUser -p$dbPass -B -N -e \
"SELECT MIN(\`DateTime\`), MAX(\`DateTime\`), COUNT(*) FROM $dbTable" \
| tr ' ' '.')
min=$(tr '.' ' ' <<< $min)
max=$(tr '.' ' ' <<< $max)
echo "Min Date:" $min
echo "Max Date:" $max
echo "Total Rows:" $rows
But that hardly seems elegant or the "unix way".
Does anyone know what I'm doing wrong and why $IFS
isn't working for me, and what the correct usage is to have clean (non-hacky) and understandable code?