Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing "echo" using Java ProcessBuilder doesn't interpolate variables (outputs the string "$PATH")

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.

like image 612
Aaron Silverman Avatar asked Feb 20 '12 20:02

Aaron Silverman


1 Answers

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

like image 58
aioobe Avatar answered Oct 20 '22 14:10

aioobe