14

I have a bash script on a Linux box that runs a Jar file. When logged in as a regular user I don't have permission to run the script, but it prints the following log:

*INFO * Using JVM found at /opt/jdk6/bin/java

When I try to use the script with Sudo though, it gives:

*ERROR* Unable to locate java, please make sure java is installed and JAVA_HOME set

I've set JAVA_HOME to the same path above — can see it with echo $JAVA_HOME & it's also set as an option within the script. I'm happy that the script isn't the issue — it's a default CQ5 control script & I'm using it on dozens of other boxes without issue. Just unsure what I'm doing wrong above & presume it's something I'm missing re Linux set-up?

When I run the sudo command, does it have access to the JAVA_HOME that I set up as myself?

anotherdave
  • 6,656
  • 4
  • 34
  • 65
  • 1
    What is the exact output of `echo $JAVA_HOME` both as root and as regular user? – Andrew Logvinov Jul 13 '12 at 11:08
  • Andrew, I don't have access as the root user itself on the machine (not the sysadmin), just as a sudoer. Just found the issue over here though: http://unix.stackexchange.com/questions/6127/java-home-not-set-in-script-when-run-using-sudo Sudo was stripping the environment variable, managed it with the `sudo -E` flag – anotherdave Jul 13 '12 at 11:13
  • 1
    I believe it depends on the distro - some sudos keep envs, others don't – Raz Jul 13 '12 at 11:13

3 Answers3

32

By default, sudo will cleanup the environment of the spawned commands. Pass -E to keep it:

sudo -E env

Compare to:

sudo env
fork0
  • 3,401
  • 23
  • 23
1

"sudo -E " didn't solve the problem when JAVA_HOME was not exported. And when it was exported, "sudo " without -E works the same.

So you can add export JAVA_HOME=.../jdk<version> in your .bash_profile and .bashrc file.

In case you wondered what's the difference of .bash_profile and .bashrc, .bash_profile is executed upon login (e.g., show some diagnostic/welcome information). .bash_rc is executed when you open a new terminal (e.g., shift-ctrl-T).

In order to run some commands for both cases, you can put it in .bashrc file, and let .bash_profile source .bashrc:

if [ -f ~/.bashrc ]; then
   source ~/.bashrc
fi
Danke Xie
  • 1,757
  • 17
  • 13
-1

You could always just pass it to java explicitly like this:

sudo java -Djava.home=$JAVA_HOME Test

dessalines
  • 6,352
  • 5
  • 42
  • 59