4

I'm calling bash script B from script A. In script A (parent script) I am exporting some variables. I would like to use these variables in script B (subscript), but the variable values are not being passed on from script A to script B. Is there a way to access the variable values from script B?

#!/bin/bash
# script_A.sh
export VAR="value"
enter code here
sudo -u user ./script_B.sh

#!/bin/bash
# script_B.sh
echo $VAR    # this prints nothing

3 Answers 3

9

As @geekosaur mentioned, sudo resets the environment for security reasons. To preserve the environment pass -E switch to sudo.

from the sudo manpage:

-E

The -E (preserve environment) option indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the -E option is specified and the user does not have permission to preserve the environment.

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

Comments

3

The problem here is not with the shell script, but that for security reasons sudo sanitizes the environment it passes to the program it runs. See man sudoers for details, and /etc/sudoers on your system for what (if any) environment variables it will preserve.

1 Comment

geekosaur is right. adding the -E file to the sudo command will preserve the environment and pass it to the subscript.
0

If you want to keep only a specific set of variables (rather than all of them) for reasons of security or simplicity, you can simply assign them as part of the sudo command:

$ cat test.sh 
#!/usr/bin/env bash
echo "$foo"
$ unset foo
$ foo=bar ./test.sh
bar
$ sudo foo=bar ./test.sh
bar

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.