sudo and environment variables
Posted on | October 10, 2009 | Views (389)
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.
In fact, I have found two solutions to preserve the evnironments varialbes exported in the parent shell.
Solution 1: add an option for sudo
sudo -E ./example.sh
Solution 2: invoke an interactive sub shell
#!/bin/bash -i
echo $JAVA_HOME
Hints and further questions:
According to the above two solutions, the lost of variables may be caused by sudo or bash or both. To explain these two solutions, I think, we should firstly figure out the behavior of sudo especially the effect of env_reset in /etc/sudoers and then how the variables settings are handed form parent shells to sub shells.
Hopefully you can get your problem resolved and if you know why, please teach me.
Comments
Leave a Reply
Hi everyone, I'm Hui, a student originally from China, now studying at TELECOM SudParis in France. Hui-Wang.info is being used as a place to record my various adventures with technology.