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.