How to invoke a Linux shell command from Java

Narek picture Narek · Sep 11, 2009 · Viewed 167.6k times · Source

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.

Answer

KitsuneYMG picture KitsuneYMG · Sep 11, 2009

exec does not execute a command in your shell

try

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

instead.

EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});