How to Run Linux Commands in Java

How do i run a Linux terminal cmd from a java program

You can use the below command format to run your Linux command.

Runtime r = Runtime.getRuntime();
Process p = r.exec(yourcmd);

Please go through Running unix command from Java and Unable to run Unix command in Java-Stackoverflow

Hope you get your answers here.

How to run linux command from java

Only a shell understands pipes, you can invoke the shell with the command you want to run:

exec(new String[]{"/bin/sh", "-c", "rpm -qa | grep \"Uploader\" | xargs rpm --queryformat \"%{VERSION}\" -q"});

run linux command from java

I hope you are familiar with vi. If not, ignore the 3rd command given below and just copy Main.java file to /Users/your-user-directory/

cd ~
pwd
vi Main.java
javac Main.java
java Main

Main.java

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main {
public static void main(String[] args) {
String s;
Process p;
String cmd = "ls";

try {
Runtime run = Runtime.getRuntime();
p = run.exec(cmd);
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

while ((s = br.readLine()) != null) {
System.out.println("line: " + s);
}

p.waitFor();
System.out.println("exit: " + p.exitValue());
p.destroy();

} catch (Exception e) {
System.out.println(e);
}
}
}

How to invoke a Linux shell command from Java

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"});

How to execute Shell Commands with Java and print the output directly while executing the command

Consider the following code.

ProcessBuilder pb = new ProcessBuilder("ping", "localhost");
pb.inheritIO();
try {
Process p = pb.start();
int exitStatus = p.waitFor();
System.out.println(exitStatus);
}
catch (InterruptedException | IOException x) {
x.printStackTrace();
}

I believe the above does what you want and I would say that the code is a lot simpler.

Refer to the javadoc for class java.lang.ProcessBuilder.



Related Topics



Leave a reply



Submit