0

I am trying to use sudo -u postgres to run all postgresql commands inside a container and I'd like to inherit all environment variables before the sudo.

I need to sudo in the first place because some of postgres cannot be run as root:

root@473f05e08ea1:/# pg_ctl
pg_ctl: cannot be run as root

Hence the use of sudo -u postgres as suggested here. The first issue encountered is that PATH env variables are different after sudo, and postgres commands cannot be found:

root@473f05e08ea1:/# sudo -u postgres pg_ctl
sudo: pg_ctl: command not found

After some search, one can use -E option to inherit PATH:

root@473f05e08ea1:/# sudo -u postgres -E env "PATH=$PATH" pg_ctl
pg_ctl: no operation specified

This makes me wonder:

Is there a way to inherit ALL environment variables (including PGDATA, PGOPTIONS, HOME etc. etc.)? Or do I have to inherit them one by one via trial-and-errors?

Related:

Why are PATH variables different when running via sudo and su?

-- Update --

The output of diff -u <(sudo -E env) <(env) is:

root@2f8a4b93e1da:/# diff -u <(sudo -E env) <(env)
--- /dev/fd/63  2023-03-18 20:36:44.898156660 +0000
+++ /dev/fd/62  2023-03-18 20:36:44.898156660 +0000
@@ -8,12 +8,5 @@
 TERM=xterm
 SHLVL=1
 PGDATA=/var/lib/postgresql/data
-PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
-_=/usr/bin/sudo
-LOGNAME=root
-USER=root
-SHELL=/bin/bash
-SUDO_COMMAND=/usr/bin/env
-SUDO_USER=root
-SUDO_UID=0
-SUDO_GID=0
+PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/postgresql/15/bin
+_=/usr/bin/env
tinlyx
  • 678

1 Answers1

0

Your second command,

sudo -u postgres -E env "PATH=$PATH" pg_ctl 

is functioning as it should.

You simply haven't specified an option for the command pg_ctl as is indicated by the error message.

To clarify this, if you

su -l postgres

and then run the command

/usr/lib/postgresql/15/bin/pg_ctl 

or

su -l postgres 

and then

export PATH=/usr/lib/postgresql/15/bin:$PATH 

followed by

pg_ctl

you'll get the same error for the same reason.

See the man page of pg_ctl for available options during use.

Nasir Riley
  • 11,422