Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hello I'm using a unix command to execute an postgres psql script, which creates a DB, in theory it could be more complex, after this command i am using ">>" to save the output on a file, the thing is it only save when the database succeeded on creation but when it fails because it already exists doesn't store anything.

Here's an example of the full command

sudo -u postgres psql -f /home/user/script.sql >> /home/user/output.txt 

in the script i just have "create database db2;"

I'm Using Ubuntu 14.04 and Postgres 9.3.4

Any hint or help would be great. Or if any information needed i will gladly answer you.

share|improve this question

1 Answer 1

up vote 0 down vote accepted

You need to redirect stderr also, in which case there should be some error output from that case where the db already exists in the text file.

sudo -u postgres psql -f /home/user/script.sql >> /home/user/output.txt 2>&1

You could also wrap the command in a bash script which checks for DB existence first before running the command.

In general when running just about any command where you're outputting to a file, you'll either want to redirect stderr to stdout or redirect stderr to a separate file (depending on how you want to consume any error output). Keep in mind that some programs (psql, pg_dump, etc. included), will sometimes log warning and info messages to stderr, so the mere presence of stderr output doesn't always mean that there was a problem per se.

share|improve this answer
    
Thank you, that worked I refused to make a bash script so i could keep it simple for the use it has. –  jarmc92 Jun 16 at 23:58
    
@jarmc92: Sure, no problem. Since it resolved your issue, please accept my answer. (stackoverflow.com/tour has more info on how to do that) –  Ken Hampson Jun 17 at 0:00
    
It's more convenient to use ` >& output.txt` by the way. Redirects both stdout and stderr. –  Craig Ringer Jun 17 at 2:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.