1

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)

  • Your 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. – Byte Commander May 7 '18 at 16:15
  • Actually myVar should be expanded as it should contains another variabIe value I've edited my question .. – storm May 7 '18 at 16:19
  • Oh, missed that. But then you still may not have the echo $myvar within the double quotes. – Byte Commander May 7 '18 at 16:27
2

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.

|improve this answer|||||
1

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"
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.