Send all error messages to a text file?

6

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?

Richard

Posted 2012-05-25T14:33:30.093

Reputation: 145

Answers

14

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

slhck

Posted 2012-05-25T14:33:30.093

Reputation: 182 472

1+1, but using '&>' to redirect both streams is arguably not valid shell syntax. dash for one will parse the & as a terminator so that ls &> foo becomes 2 commands: ls is run in the background and foo is truncated. It is not safe to use that construct. Personally, I believe the dash semantics are correct, but enough shells conflict with the language spec on this case that "ambiguous" is the only reasonable adjective to describe the parsing without triggering an unholy flame war. Avoid '&>' – William Pursell – 2012-05-28T17:09:55.100

1Yeah, I said, "most shells", but I know what you mean. There are plenty of pitfalls anyway with respect to shell scripting and portability, so I guess you're right that it shouldn't be used. – slhck – 2012-05-28T18:57:00.647