salivan salivan - 4 months ago 7
Bash Question

bash conditional doesn't work inside while

Inside while I get 1 printed in infinite loop, so why is not this comparison functioning correctly?

while [[ "$(mysql -u root -e "select 1")" != 1 ]]; do
mysql -u root -e "select 1"
sleep 1
done


Output

1
1
1
1
1
1
1
1
1
1
1
1

0000000 1 \n 1 \n
0a31 0a31
0000004
0000000 1 \n 1 \n
0a31 0a31
0000004
0000000 1 \n 1 \n
0a31 0a31
0000004
0000000 1 \n 1 \n
0a31 0a31
0000004
0000000 1 \n 1 \n
0a31 0a31
0000004
0000000 1 \n 1 \n
0a31 0a31
0000004
0000000 1 \n 1 \n
0a31 0a31

Answer

The MySQL select statement select 1 will return two things:

  1. A column name.
  2. A value.

The column name is 1, and the value is also 1.

To avoid getting the column name in the output use the --skip-column-names (or -N) option to mysql.

You might also want to use --batch (-B) as this disables the generation of an ASCII-formatted table for those that hasn't this turned off by default:

$ mysql (options) -e 'select 1'
+---+
| 1 |
+---+
| 1 |
+---+

$ mysql -N (options) -e 'select 1'
+---+
| 1 |
+---+

$ mysql -B -N (options) -e 'select 1'
1
Comments