As a normal user, we have to use privilege-gaining tools such as sudo to run programs as the root user when required. With the super user rights in hand, are we still working in the same environments set by the normal user ?
The reason why I ask this question is that I’m losing the environment variables set in ~/.bashrc when running a bash script with sudo. For instance, the variable JAVA_HOME is set and exported in ~/.bashrc.
export JAVA_HOME=/usr/lib/jvm/java-6-sun
A bash script called example.sh will use this variable to find java home directory.
#!/bin/bash
echo $JAVA_HOME
When example.sh is invoked by the current user by typing
./example.sh
the output is exactly the expected one:
/usr/lib/jvm/java-6-sun
However, when trying with
sudo ./example.sh
We get nothing. The variable is lost or in a other word, not inherited.
Solution:
Use the following sudo option
sudo -E ./example.sh
You could also use an interactive sub shell, but thats not a recommended option. I will provide that option any ways..
invoke an interactive sub shell
#!/bin/bash -i
echo $JAVA_HOME
No comments:
Post a Comment