views:

1020

answers:

2

I am trying to exec some linux commands from Java code. Actualy the code that I use is useing redirection (>&) and pipe simbols (|). How my Java code should be to be able to invoke that command as in csh or bash. Thanks in advance.

P.S. I have used:

Process p = Runtime.getRuntime().exec("shell command");

but this code is not OK with redirections and piping.

+7  A: 

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"});
KitsuneYMG
doesn't work, sorry
Narek
@Narek. Sorry about that. I fixed it by removing the extra \" 's Apparently they aren't needed. I don't have csh on my system, but it works with bash.
KitsuneYMG
As others has mentioned this should be independent wether you have csh or bash, isn't it?
Narek
@Narek. It should, but I don;'t know how csh handles arguments.
KitsuneYMG
+1  A: 

Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:

 //Build command 
 List<String> commands = new ArrayList<String>();
 commands.add("/bin/cat");
 //Add arguments
 commands.add("/home/narek/pk.txt");
 log.debug("{}", commands);

 //Run macro on target
 ProcessBuilder pb = new ProcessBuilder(commands);
 pb.directory(directory);
 pb.redirectErrorStream(true);
 Process process = pb.start();

 //Read output
 StringBuilder out = new StringBuilder();
 BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
 String line = null, previous = null;
 while ((line = br.readLine()) != null)
  if (!line.equals(previous)) {
   previous = line;
   out.append(line).append('\n');
   log.debug(line);
  }

 //Check result
 if (process.waitFor() == 0)
  return 0;

 //Abnormal termination: Log command parameters and output and throw ExecutionException
 log.error("{}", commands);
 log.error("\n{}", out.toString());
 throw new ExecutionException(new IllegalStateException("Yasara macro exit code 1"));
Tim