Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass environment variable to sudo

I must pass an environment variable to sudo, but I am not successful and cannot understand how to get it working:

$sudo TEST=MY_TEST --user=myuser --login echo "$TEST"
$

The output is empty, but export shows me the following:

$sudo TEST=MY_TEST --user=myuser --login export
...
declare -x TEST="MY_TEST"
...

The environment variable should not be declared in the calling shell. It should be declared locally and directly passed to the sudo command. Can someone help me to pass an environment variable to sudo without using export in the calling shell.

like image 773
Herr-Herner Avatar asked Nov 16 '16 05:11

Herr-Herner


1 Answers

As you have used double quotes the variable expansion, "$TEST", the expansion is happening before the sudo command runs, so the echo is seeing the argument as empty as the variable expansion already resulted in null string.

You can leverage a shell here:

% sudo TEST=MY_TEST sh -c 'echo "$TEST"'              
MY_TEST
like image 185
heemayl Avatar answered Nov 04 '22 16:11

heemayl