how to pass environment variable to sudo su
Pro tip: There is never really a good reason to run sudo su
. To run a command as a different user, use sudo -u username command
. If you want a root shell, run sudo -i
or sudo -l
. If you have activated the root account, you can also run su
alone, but sudo su
is just not useful. And yes, I know you see it everywhere.
That said, sudo
has the -E
switch which will preserve the environment of the user's session:
-E, --preserve-env
Indicates to the security policy that the user wishes to preserve
their existing environment variables. The security policy may
return an error if the user does not have permission to
preserve the environment.
So, you will first need to export your variable, and then run sudo -E
:
$ export DUMMY=dummy
$ sudo -Eu bob bash -c 'echo $DUMMY'
dummy
The bash -c
is not needed. However, if I run sudo -Eu bob echo "$DUMMY"
, the variable is expanded before the root shell is launched so it doesn't demonstrate that the command actually works:
$ sudo -u bob echo $DUMMY ## looks like it works but doesn't
dummy
$ sudo -u bob bash -c 'echo D:$DUMMY' ## now we see it failed
D:
$ sudo -Eu bob bash -c 'echo D:$DUMMY' ## works as expected
D:dummy
You can do it without calling login shell:
sudo DUMMY=dummy su ec2-user -c 'echo "$DUMMY"'
or:
sudo DUMMY=dummy su -p - ec2-user -c 'echo "$DUMMY"'
The -p
option of su
command preserve environment variables.
-E does the job for me.
From man sudo
-
-E
,--preserve-env
Indicates to the security policy that the user wishes to pre‐ serve their existing environment variables. The security policy may return an error if the user does not have permis‐ sion to preserve the environment.