Send all error messages to a text file

bashcommand lineshell

I'm trying to run the following command:

$ psql -d template_postgis -f /usr/local/pgsql-9.1/share/contrib/postgis-2.0/postgis.sql 

It produces a vast amount of error output, of which I can only see the end within my shell – I need to see the beginning to work out what's going wrong.

... 
psql:/usr/local/pgsql-9.1/share/contrib/postgis-2.0/postgis.sql:6065: ERROR:  current transaction is aborted, commands ignored until end of transaction block
psql:/usr/local/pgsql-9.1/share/contrib/postgis-2.0/postgis.sql:6075: ERROR:  current transaction is aborted, commands ignored until end of transaction block
psql:/usr/local/pgsql-9.1/share/contrib/postgis-2.0/postgis.sql:6081: ERROR:  current transaction is aborted, commands ignored until end of transaction block

However, if I try to send the messages to a text file:

$ psql -d template_postgis -f /usr/local/pgsql-9.1/share/contrib/postgis-2.0/postgis.sql > error.txt

The text file only contains three commands:

SET
BEGIN
ROLLBACK

So why isn't all the output being sent to the text file, and how can I see all the output?

Best Answer

In Unix (and others), there are typically two output streams you want to use, STDOUT and STDERR. Both are standard streams.

With > you only redirect STDOUT to a file.

With 2> you redirect STDERR to a file (the "2" because its file descriptor is "2").


Actually, there's STDIN too, which you can redirect with <. This graphic shows how they typically interact.

diagram

Since error messages should always be printed to STDERR (and most programs respect that), try something along this to separate normal output and error output:

command > normal.log 2> err.log

Similarly, you can redirect STDERR to STDOUT.

command 2>&1 > out.log

As a shorthand, you could also redirect everything into one file right away – at least with most shells. Don't rely on this for portability though.

command &> out.log
Related Question