How to export env variables as another user
Solution 1
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
.
Solution 2
As Byte Commander explained, you have to put the command in single quotes to prevent Bash from expanding the variable. If $toto
has to be expanded in the original shell, provide it as an argument outside the command list and access it as $0
:
su - myUser -c 'export myVar="$0"; echo $myVar' "$toto"
Related videos on Youtube
storm
Updated on September 18, 2022Comments
-
storm over 1 year
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
myUser
and 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)-
Byte Commander almost 6 yearsYour echo works if you put the command in single quotes to prevent Bash from expanding the variable before running the command:
su - myUser -c 'export myVar=toto ; echo $myVar'
. No idea about the script file, that is probably a different issue. -
storm almost 6 yearsActually myVar should be expanded as it should contains another variabIe value I've edited my question ..
-
Byte Commander almost 6 yearsOh, missed that. But then you still may not have the
echo $myvar
within the double quotes.
-