Redirect error out to standard output

io-redirectionMySQL

I can save the error out in the same file as standard out. I have used this method below.
The problem is that the error out is "always" shown at the top. In the example given below the error relates to the second last sql command where value "india" can not be saved. The error message should be shown next to that statement and not at the top of the file.

# cat import.txt
drop table if exists testme;
create table testme (id int , name varchar(255));
insert into testme values (1, 'abc');
insert into testme values (2, 'abc', 'india');
insert into testme values (3, 'xyz');

# mysql test -vvf  < import.txt  >standard.txt 2>&1

# cat standard.txt
ERROR 1136 (21S01) at line 5: Column count doesn't match value count at row 1
--------------
drop table if exists testme
--------------

Query OK, 0 rows affected

--------------
create table testme (id int , name varchar(255))
--------------

Query OK, 0 rows affected

--------------
insert into testme values (1, 'abc')
--------------

Query OK, 1 row affected

--------------
insert into testme values (2, 'abc', 'india')
--------------

--------------
insert into testme values (3, 'xyz')
--------------

Query OK, 1 row affected

The expected output will look something like this…

# mysql test -vvf  < import.txt
--------------
drop table if exists testme
--------------

Query OK, 0 rows affected

--------------
create table testme (id int , name varchar(255))
--------------

Query OK, 0 rows affected

--------------
insert into testme values (1, 'abc')
--------------

Query OK, 1 row affected

--------------
insert into testme values (2, 'abc', 'india')
--------------

ERROR 1136 (21S01) at line 4: Column count doesn't match value count at row 1
--------------
insert into testme values (3, 'xyz')
--------------

Query OK, 1 row affected

The error out should be placed exactly next to the statement that it relates to. Or else the redirected output file is not useful.

Best Answer

This actually has nothing to do with the shell, it's a 'feature' of the mysql command line utility.

Basically when mysql detects that the output isn't going to a terminal, it enables output buffering. This improves performance. However the program apparently sends the success output to STDOUT, and the error output to STDERR (makes sense really), and keeps a separate buffer for each.

The solution is simply to add -n to the mysql command arguments. The -n (or --unbuffered) option disables output buffering.

For example:

mysql test -nvvf  < import.txt  >standard.txt 2>&1
Related Question