3

I have a Ubuntu server that processes documents and another that have the database (postgresql 9.3).

I ran psql -? to understand how to connect to another DB and the final command would be:

psql -U postgres -W -h 1.2.3.4 -d testdb -p 5432

It works, but I must type the password after the command is issued.

I was trying to adapt this command in a bash script:

#!/bin/bash
psql -U postgres -W mypassword -h 1.2.3.4 -d testdb -p 5432 << EOF
select * from mytable;
\q
EOF

Needless to say this is not the right command. Also, the password does not get recognized as a password, reporting the error:

psql: warning: extra command-line argument "mypassword" ignored
Password for user postgres: 
psql: FATAL:  password authentication failed for user "postgres"
FATAL:  password authentication failed for user "postgres"

In another server, where the script runs on the local DB, my working script is:

su - postgres -c "psql myDatabase" << EOF
select * from "myOtherTable";
\q
EOF

The question is simple, how can I write the right command for bash, to connect to another database with user/password and issue commands?

A link I tried, but password seems to not be set: run psql query in bash

Thanks!

1 Answer 1

4

Try

PGPASSWORD=yourpass psql -U postgres -W -h 1.2.3.4 -d testdb -p 5432

See: https://www.postgresql.org/docs/9.3/static/libpq-envars.html

or ~/.pgpass file https://www.postgresql.org/docs/9.3/static/libpq-pgpass.html

Sign up to request clarification or add additional context in comments.

2 Comments

good links! thanks i check them out and when working will mark your answer (:
At first it kept asking for the password, then it just stopped. Test server rebooted, script ran and worked! I tried the .pgpass solution. creating this file in the root folder, permissions to 0600 and the command in the script is psql -U postgres -h 1.2.3.4 -d dbname << eof [...] \q eof

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.