Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to run an install script that requires java to be installed and the JAVA_HOME environment variable to be set.

I've set JAVA_HOME in /etc/profile and also in a file I've called java.sh in /etc/profile.d. I can echo $JAVA_HOME and get the correct response and I can even sudo echo $JAVA_HOME and get the correct response.

In the install.sh I'm trying to run I inserted an echo $JAVA_HOME. When I run this script as myself I see the java directory, but when I run the script with sudo it is blank.

Any ideas why this is happening?

I'm running CentOS

share|improve this question
add comment

2 Answers

up vote 12 down vote accepted

For security reasons, sudo may clear environment variables which is why it is probably not picking up $JAVA_HOME. Look in your /etc/sudoers file for env_reset.

From man sudoers:

env_reset   If set, sudo will reset the environment to only contain the following variables: HOME, LOGNAME, PATH, SHELL, TERM, and USER (in addi-
           tion to the SUDO_* variables).  Of these, only TERM is copied unaltered from the old environment.  The other variables are set to
           default values (possibly modified by the value of the set_logname option).  If sudo was compiled with the SECURE_PATH option, its value
           will be used for the PATH environment variable.  Other variables may be preserved with the env_keep option.

env_keep    Environment variables to be preserved in the user's environment when the env_reset option is in effect.  This allows fine-grained con-
           trol over the environment sudo-spawned processes will receive.  The argument may be a double-quoted, space-separated list or a single
           value without double-quotes.  The list can be replaced, added to, deleted from, or disabled by using the =, +=, -=, and ! operators
           respectively.  This list has no default members.

So, if you want it to keep JAVA_HOME, add it to env_keep:

Defaults   env_keep += "JAVA_HOME"

Alternatively, set JAVA_HOME in root's ~/.bash_profile.

share|improve this answer
    
Yea, that was it. Had no idea one could do that. Thanks! –  Josh Jan 19 '11 at 16:23
add comment

Run sudo with the -E (preserve environment) option (see the man file), or put JAVA_HOME in the install.sh script.

share|improve this answer
    
Thanks, this would have been a nice solution as well. –  Josh Jan 19 '11 at 16:41
    
The -E option is not available in CentOS. –  Zubin May 5 '11 at 20:40
    
This did it for me, thanks :) –  anotherdave Jul 13 '12 at 11:11
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.