How to use psql with no password prompt?
-
16-10-2019 - |
Question
I wrote a script to REINDEX
indexes in a database. Here is one of them:
echo -e "\nreindex for unq_vbvdata_vehicle started at: `date "+%F %T"`" >> ${LOG_FILE}
psql -U ${USERNAME} -h ${HOSTNAME} -d ${DBNAME} -c "REINDEX INDEX scm_main.unq_vbvdata_vehicle;"
if [[ ${?} -eq 0 ]]; then
echo "reindex for unq_vbvdata_vehicle finished at: `date "+%F %T"`" >> ${LOG_FILE}
else
echo "reindex for unq_vbvdata_vehicle failed" >> ${LOG_FILE}
exit 1
fi
The problem is I can not run this script in standalone mode. psql
is prompting password every time it runs. There is also two limitations:
I can not create a user on database with no password.
Because
REINDEX
locks tables, I should usesleep <num>
between eachREINDEX
.
Is there any automatic solution?
Solution
You have four choices regarding the password prompt:
- set the PGPASSWORD environment variable. For details see the manual:
http://www.postgresql.org/docs/current/static/libpq-envars.html - use a .pgpass file to store the password. For details see the manual:
http://www.postgresql.org/docs/current/static/libpq-pgpass.html - use "trust authentication" for that specific user:
http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-TRUST - use a connection URI that contains everything:
http://www.postgresql.org/docs/current/static/libpq-connect.html#AEN42532
OTHER TIPS
A simple example with PGPASSWORD
will be something like:
PGPASSWORD=YOUR_PASSRORD psql -h YOUR_PG_HOST -U YOUR_USER_NAME
Hope it helps.
Depending your account permissions, the example without specifying the database may fail, because user permissions are checked against the database you connect to. It is better explicitly specify the database too.
# this can fail.
PGPASSWORD=YOUR_PASSRORD psql -h YOUR_PG_HOST -U YOUR_USER_NAME
# this is more likely to work, assuming given account has permissions to that database.
PGPASSWORD=YOUR_PASSRORD psql -h YOUR_PG_HOST -U YOUR_USER_NAME -d YOUR_DATABASE
Very helpful answers in this thread. I'm just adding this for ubuntu 18.04:
sudo PGPASSWORD=yourpasswordHere -u postgres psql
This will take you into the postgres without the password prompt, without having to set any environment variables. This is not a permanent setting.