I am trying to execute some Linux commands from Java using redirection (>&) and pipes (|). How can Java invoke csh
or bash
commands?
I tried to use this:
Process p = Runtime.getRuntime().exec("shell command");
But it's not compatible with redirections or pipes.
exec does not execute a command in your shell
try
instead.
EDIT:: I don't have csh on my system so I used bash instead. The following worked for me
Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:
Building on @Tim's example to make a self-contained method:
(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)
By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.
Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.