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.

1
  • Instead of "echo $path", just try path, if you are using windows. Commented Feb 20, 2012 at 21:09

1 Answer 1

8

$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.

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

2 Comments

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
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.

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.