How can I call psql so that it doesn\'t prompt for a password?
This is what I have:
psql -Umyuser < myscript.sql
It can be done simply using PGPASSWORD. I am using psql 9.5.10. In your case the solution would be
PGPASSWORD=password psql -U myuser < myscript.sql
This might be an old question, but there's an alternate method you can use that no one has mentioned. It's possible to specify the password directly in the connection URI. The documentation can be found here, alternatively here.
You can provide your username and password directly in the connection URI provided to psql
:
# postgresql://[user[:password]@][netloc][:port][/dbname][?param1=value1&...]
psql postgresql://username:password@localhost:5432/mydb
If you're having problems on windows like me (I'm using Windows 7 64-bit) and set PGPASSWORD=[Password]
did not work.
Then, as Kavaklioglu said in one of the comments,
export PGPASSWORD=[password]
You will need to save this at the top of the file, or before any usage so its set before being called.
Certainly does work on windows :)
Building on mightybyte's answer for those who aren't comfortable with *nix shell scripting, here's a working script:
#!/bin/sh
PGPASSFILE=/tmp/pgpasswd$$
touch $PGPASSFILE
chmod 600 $PGPASSFILE
echo "myserver:5432:mydb:jdoe:password" > $PGPASSFILE
export PGPASSFILE
psql mydb
rm $PGPASSFILE
The double dollar sign ($$
) in /tmp/pgpasswd$$
at line 2 appends the process ID number to the file name, so that this script can be run more than once, even simultaneously, without side effects.
Note the use of the chmod
command at line 4 - just like the "not a plain file" error that mightybyte described, there's also a "permissions" error if this is not done.
At line 7, you won't have to use the -h
myserver, the -p
myport, or -U
jdoe flag if you use the defaults (localhost : 5432) and only have one database user. For multiple users, (but the default connection) change that line to
psql mydb jdoe
Don't forget to make the script executable with
chmod +x runpsql
(or whatever you called the script file)
UPDATE:
I took RichVel's advice and made the file unreadable before putting the password into it. That closes a slight security hole. Thanks!