Ubuntu – How to export env variables as another user

bashcommand lineenvironment-variablesscripts

I'm trying to set an environment variable for a user session before running a script:

su - myUser -c "export myVar=$toto ; sh scriptThatNeedsMyVar.sh"

The scripts fails, I tried to debug and print myVar value:

su - myUser -c "export myVar=$toto ; echo $myVar"

returns nothing, that means that my env variable wasn't created although I'm creating and printing it in the same bash !
Then when I login as myUserand type each command in bash console it works well

$su - myUser
$export myVar=toto
$echo $myVar
toto

I'm I missing something ?
Why is this happening and how can I export a temporary variable as another user ( I'm not allowed to edit bashrc or any other system file)

Best Answer

use env:

su - myUser -c "env myVar=\"$toto\" scriptThatNeedsMyVar.sh"

Assuming, of course, that scriptThatNeedsMyVar.sh is executable, and findable in myUser's PATH, and begins with #!/bin/sh.

Related Question