6

I want to echo the PATH variable, with the goal to get the same output from a Java ProcessBuilder as running echo $PATH in the terminal. However, when it executes the output is actually $PATH instead of the value of the PATH variable. I wonder if ProcessBuilder is escaping the $ and is there a trick to prevent this?

Here is a code sample of what I am talking about that outputs the string "$PATH":

List<String>  processBuilderCommand = ImmutableList.of("echo","$PATH");

ProcessBuilder processBuilder = new ProcessBuilder(processBuilderCommand).redirectErrorStream(true);

final Process process = processBuilder.start();

String commandOutput = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
                @Override
                public InputStream getInput() throws IOException {
                    return process.getInputStream();
                }
            }, Charset.defaultCharset()));

System.out.println(commandOutput);

Some extra context:

I am trying to simulate the sort command not being found for one of my unit tests. I am using this hack/trick to change my PATH and by inspecting the result of processBuilder.environment() and sure enough the PATH variable being passed to the process shouldn't allow finding sort (I've tried the empty string as well as a random path). I'd like to see if the shell is doing anything funny and fixing back up PATH which I am trying to destroy.

Community
  • 1
  • 1
Aaron Silverman
  • 22,070
  • 21
  • 83
  • 103

1 Answers1

7

$PATH is the syntax used in bash (and other shells) to refer to the environment variable PATH. Since it's echo you execute using the ProcessBuilder, and not bash it's not very surprising that it doesn't print the content of the environment variable.

You should either get hold of the content of the environment variable from Java, and give it as argument to the external process, or, execute a program which is capable of interpreting the $PATH syntax properly, (such as bash).


As pointed out in your comment below,

[...]  ImmutableList.of("/bin/bash","-c","echo $PATH")  [...]

indeed prints the content of the PATH environment variable.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Great point! I tried again with processBuilderCommand = ImmutableList.of("/bin/bash","-c","echo $PATH"); and it output the path as expected. Now I am just more baffled that it can find the sort command :-P – Aaron Silverman Feb 20 '12 at 21:12
  • Ah, nice that you found the `-c` switch and managed to let bash resolve the PATH. I'll updated the answer with your solution if someone else stumbles across your question but doesn't bother reading your comment. – aioobe Feb 20 '12 at 21:14