Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I am writing a non-interactive script that needs to execute postgres commands. The script will only be run by root or a user with sudo permissions, and the postgres commands need to be executed as the postgres user in postgresql. The trouble is that postgresql always (as far as I can tell) prompts for a password interactively (i.e. pqsl -U postgres -W) or does not accept a password at all (i.e. psql -U postgres -w). I would like to pass a password on the command line, similar to how mysql allows mysql -u user -p password. How can I do this with postgres?

share|improve this question
1  
What language are you using? Shell? –  Faheem Mitha Apr 22 '14 at 17:56
    
You shouldn't do that. -p password leaves your password visible in, for example, ps xa output. –  derobert Apr 22 '14 at 17:59
    
I'm using a bash script. And @derobert, so if I shouldn't do it this way, then how do I run postgres commands non-interactively at all? I'm going to need to authenticate to the postgres server somehow. –  jayhendren Apr 22 '14 at 18:02
    
@jayhendren you can set up your pg_hba.conf file to use peer or ident authentication (if the script is running on the same machine as postgres) or you can use a ~/.pgpass file. –  derobert Apr 22 '14 at 18:05

1 Answer 1

up vote 1 down vote accepted

Use the PGPASSWORD environment variable. For instance:

PGPASSWORD=<password> psql -U postgres -c "<postgresql query>"

Source

share|improve this answer

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.