Herr-Herner
Herr-Herner

Reputation: 481

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.

Upvotes: 6

Views: 5084

Answers (1)

heemayl
heemayl

Reputation: 42017

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

Upvotes: 8

Related Questions