-1

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.

1 Answer 1

0

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.

2
  • Thank you, that worked I refused to make a bash script so i could keep it simple for the use it has. Commented Jun 16, 2014 at 23:58
  • It's more convenient to use ` >& output.txt` by the way. Redirects both stdout and stderr. Commented Jun 17, 2014 at 2:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.