I have a bash script/s which has a "main" script which is run as sudo.
Variables are declared in this script.
Then it sources another commands.sh script, however this script uses sudo to drop back to an ordinary user when sourcing the commands.sh script.

file: main.sh


export $user

sudo -u $user bash -c "source includes-shared/commands.sh"

file: includes-shared/commands.sh

# debug command to see if $user is available
[ more commands...]

The variable $user no longer appears in this commands.sh script, i.e. it is not visible to printenv or other commands.
How can I export $user so that it is available to the sourced script?


You need to run export against the name of the variable. Right now, the variable is being referenced and replaced before export sees it.

Change it to this:

export user

Note the lack of $

Your current version is essentially this:

export ubuntu

Because $user is interpreted first.

You also lost your environmental variables when using sudo. There are two ways to preserve them. Either keep your entire environment

sudo -E -u $user command

Or just keep the variable you need

sudo user=$user -u $user command
  • thanks, that definitely makes sense, but I still get the same result when I don't use the $ Apr 18 '16 at 6:40
  • @the_velour_fog Sorry I'm used to using su instead of sudo so I missed a step! Apr 18 '16 at 6:49
  • no problem, sudo -E -u $user command worked perfectly, thanks! Apr 18 '16 at 6:56

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.