2

I have a bash script env_setter.sh. It sets an environment variable. It contains:

#!/bin/bash
echo "inside env_setter script....."
export NAME="jake"

I have another script tester.sh. It tries to print the value of the environment variable set by env_setter.sh. It contains:

#!/bin/bash
echo "Inside tester script..."
echo "$NAME"

Then I have a script runner.sh that executes both of the above scripts as follow:

#!/bin/bash
echo "Inside runner script..."
. ./env_setter.sh
echo "$NAME"
sudo nohup ./tester.sh > demo.log 2>&1 & echo $! > save_pid.pid

Now when I run runner.sh, I get following output in demo.log:

inside env_setter script.....
jake
Inside tester script...

As we can see, the last echo command in tester.sh doesn't print anything. This is because the environment variable that we set with env_setter.sh is not being exported inside the context of tester.sh.

So, how do I export the environment variable to the background process in such cases?

5
  • 4
    Normally sudo replaces the current environment with the environment of the user, for security reasons. Use sudo -E to preserve the calling environment. Or you can pass variables on the command line, sudo NAME=jake. Commented Sep 1, 2018 at 14:15
  • 1
    What you are looking for is to pass one variable from one script to another script. This has already been asked and answered here: stackoverflow.com/questions/9772036/… Commented Sep 1, 2018 at 14:46
  • @JimJanney sudo -E worked for me. Thanks ! Commented Sep 1, 2018 at 14:55
  • @JimJanney Would you please add that as an answer so the OP can check it off? Thanks! Commented Sep 1, 2018 at 18:11
  • 3
    Possible duplicate of Can I export a variable to the environment from a bash script without sourcing it? and How to keep environment variables when using sudo Commented Sep 1, 2018 at 21:39

1 Answer 1

4

Normally sudo replaces the current environment with the environment of the new user, for security reasons. Use sudo -E to preserve the calling environment. Or you can pass variables on the command line, sudo NAME=jake.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.