1

I have a Java program that spawns a bash script that calls another script. In that second script, I'm finding that the $HOME variable is not set. Here's the gist of it:

In Java:

Process p = new ProcessBuilder("bash", "-l", "/foo/a.sh").start();
// code to actually execute p

/foo/a.sh:

#!/bin/bash
/foo/b.sh

/foo/b.sh:

#!/bin/bash
echo "HOME=$HOME"

This echoes "HOME=". The eventual problem is that $HOME/bin is supposed to be added to my PATH in ~/.profile, but since that's not happening, a bunch of custom executables aren't being made accessible.

I worked around it by doing:

if [ -d ~/bin ] ; then
    PATH=~/bin:"$PATH"
fi

And that works fine. But I guess I just want to understand why $HOME wasn't being set. It seems like $HOME and ~ should be largely equivalent, no? There's probably something I'm fundamentally missing about how this environment is getting set up.

I am running Ubuntu 12.04.5, if that makes a difference.

2
  • At the risk of being tedious, in your Java app, you're sure that the environment prior to creating the ProcessBuilder instance contains HOME? If you examine System.getenv() contents just prior to your line of Java, what does it show? Commented Oct 16, 2014 at 1:36
  • 1
    @John1024: Not quite. Posix requires that the system (not the shell) set the HOME environment variable on login (not at startup). It's normally set by the login program or equivalent. See man login Commented Oct 16, 2014 at 4:43

1 Answer 1

4

The evidence suggests that HOME is missing from the environment in which the Java app is running. Assuming that the app doesn't explicit unset HOME, the most likely reason is that the app is being started from some context other than a login by the user the app is running as.

It's correct that ~ and $HOME are similar. If HOME is present in the environment, even if it is set to the empty string, ~ will be replaced with $HOME. However, if HOME is not present in the environment, bash will attempt to find the home directory for the currently logged in user, and use that for ~.

eg.

$ bash -c 'echo ~'
/home/rici
$ HOME='Hello, world!' bash -c 'echo ~'
Hello, world!
$ HOME= bash -c 'echo ~'

$ (unset HOME; bash -c 'echo ~';)
/home/rici

Since your workaround requires the equivalent of the last scenario, I conclude that HOME has not been set, or has been unset.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.