2

I have a java program which executes a shell script. The shell script involves many environment variables in it($HOME). When executing the command from shell, it is working fine. An echo $HOME is giving me the actual path to the command. (The script changes paths and executes commands from changed paths)

$cat nightly.sh

#!/bin/bash
...
echo $HOME
...
echo "end of script"

I see /home/ when executed from the shell at appropriate place.

Now I invoke the same shell script from java program by,

static Proces p;
...
Runtime instance = Runtime.getRuntime();                
p = instance.exec(nightly.sh + " " + branch + " " + stack + " " + profile, null, new File(/home/bmanoj/fps/workspaces/APRIL14REL1/testing/integration-tests/regressions));

Now I am capturing the output from the shell to a external file. When I go see the file "echo $HOME" is resulting to a empty line. For that matter I am constructing many relative paths based on the $HOME variable. So nothing in the script works for me now.

Why is it like that? Why isn't the instance invoked by java program not picking up the environment variables? To exactly mock the script as it executes on the shell from the java program what has to be done?

  • Environment variables belong for the user who runs the program. What user is running your Java program? – marekful Jul 18 '14 at 14:29
  • How are you running the java program? Manually? From cron? From a web request? – Etan Reisner Jul 18 '14 at 14:30
  • 1
    You are passing `null` as environment, so you want the subprocess to inherit the environment of the current process, check whether the variable is present in the current process first. – A4L Jul 18 '14 at 14:32
  • 2
    Dont use Runtime.exec instead use the `ProcessBuilder` class to execute shell scripts. Your environment variables are set in the ProcessBuilder environment automatically. See related here on how to use http://stackoverflow.com/questions/525212/how-to-run-unix-shell-script-from-java-code – Revive Jul 18 '14 at 14:36
  • The program is now running without any user. i.e., "nobody". So could that be the reason? @Marcell – deepak.prathapani Jul 21 '14 at 05:49
  • I am running the java program from the browser. A click on the submit on the web page will initiate the UNIX script. @EtanReisner – deepak.prathapani Jul 21 '14 at 05:51

0 Answers0