Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to invoke a Linux shell command from Java

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.

like image 626
Narek Avatar asked Sep 11 '09 13:09

Narek


People also ask

Can Java execute shell commands?

We've used the Runtime and ProcessBuilder classes to do this. Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.

Can we run Linux command in Java?

You can use java. lang. Runtime. exec to run simple code.

How do I run a terminal command in Java?

Type 'javac MyFirstJavaProgram. java' and press enter to compile your code. If there are no errors in your code, the command prompt will take you to the next line (Assumption: The path variable is set). Now, type ' java MyFirstJavaProgram ' to run your program.


2 Answers

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"}); 
like image 128
KitsuneYMG Avatar answered Oct 25 '22 20:10

KitsuneYMG


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

import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List;  public class Test {      public static void main(final String[] args) throws IOException, InterruptedException {         //Build command          List<String> commands = new ArrayList<String>();         commands.add("/bin/cat");         //Add arguments         commands.add("/home/narek/pk.txt");         System.out.println(commands);          //Run macro on target         ProcessBuilder pb = new ProcessBuilder(commands);         pb.directory(new File("/home/narek"));         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');                 System.out.println(line);             }          //Check result         if (process.waitFor() == 0) {             System.out.println("Success!");             System.exit(0);         }          //Abnormal termination: Log command parameters and output and throw ExecutionException         System.err.println(commands);         System.err.println(out.toString());         System.exit(1);     } } 
like image 22
Tim Avatar answered Oct 25 '22 20:10

Tim