How can I call psql so that it doesn\'t prompt for a password?
This is what I have:
psql -Umyuser < myscript.sql
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!