Sample Header Ad - 728x90

psql \set an environment variable from the existing shell environment

4 votes
1 answer
3003 views
I want to set up a psql variable from an existing shell environment variable that I can use in later psql commands. I found the \set meta-command, but I'm not able to make it use an existing environment variable in Linux:
user@localhost# MY_DB='test_database'
user@localhost# sudo -u postgres psql
\set dbname ${MY_DB}
\set 
...
dbname = '${MY_DB}'
whereas I would like dbname = 'test_database' on the last line so that I can use it or example like: \connect :dbname; How could I achieve that with pg 15 on debian 11? This is not helping me much because
\set dbname echo ${MY_DB}
is issuing an empty string. This neither, because I'd like to set my psql variable only once in order to avoid redundancy and to reuse it in plenty of psql commands instead of setting it plenty of times with -v in each of those psql commands.
Asked by s.k (424 rep)
May 25, 2023, 09:41 AM
Last activity: May 25, 2023, 11:56 AM