Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a shell script from another shell script via sudo - environment variables?

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
like image 462
user1325378 Avatar asked Dec 17 '22 01:12

user1325378


1 Answers

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.

like image 106
c00kiemon5ter Avatar answered Jan 06 '23 13:01

c00kiemon5ter