3

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?

1 Answer 1

2

You need quotes around the result of the command substitution, i.e. "$(command)" I think e.g. (simulating your query with an echo):

$ IFS=$'\t' read min max rows <<< "$(echo -e "Wed Jul 30 15:40:38 EDT 2014\tThu Jul 31 15:40:38 EDT 2014\t27")"
$ echo "$min"; echo "$max"
Wed Jul 30 15:40:38 EDT 2014
Thu Jul 31 15:40:38 EDT 2014

or use a (more direct) process substitution instead

$ IFS=$'\t' read min max rows < <(echo -e "Wed Jul 30 15:40:38 EDT 2014\tThu Jul 31 15:40:38 EDT 2014\t27")
$ echo "$min"; echo "$max"
Wed Jul 30 15:40:38 EDT 2014
Thu Jul 31 15:40:38 EDT 2014
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .