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?

cxw
  • 16,685
  • 2
  • 45
  • 81
oblivion
  • 5,928
  • 3
  • 34
  • 55
  • 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`. – Jim Janney Sep 01 '18 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: https://stackoverflow.com/questions/9772036/pass-all-variables-from-one-shellscript-to-another – Néstor Lucas Martínez Sep 01 '18 at 14:46
  • @JimJanney `sudo -E` worked for me. Thanks ! – oblivion Sep 01 '18 at 14:55
  • @JimJanney Would you please add that as an answer so the OP can check it off? Thanks! – cxw Sep 01 '18 at 18:11
  • 3
    Possible duplicate of [Can I export a variable to the environment from a bash script without sourcing it?](https://stackoverflow.com/q/16618071/608639) and [How to keep environment variables when using sudo](https://stackoverflow.com/q/8633461/608639) – jww Sep 01 '18 at 21:39

1 Answers1

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.

Jim Janney
  • 361
  • 1
  • 6