May 5, 2020

#1 Read bash environment variables in psql

To use bash environment variables in postgres/psql, make use of \set meta command.

$ db_user="vn"
$ pg_pass=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 15 ; echo '')
$ psql
postgres=# \set user `echo $db_user`
postgres=# \set pass `echo $pg_pass`
postgres=# CREATE USER :'user' CREATEDB;
postgres=# ALTER USER :'user' PASSWORD :'pass';