Execute a Linux Terminal Command 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.

Execute a linux terminal command in java?

The issue is that Runtime.exec() does not understand shell concepts such as "|". Instead try:

Runtime.getRuntime().exec("/bin/sh", "-c", co);

The problem is that exec runs a binary directly without invoking the shell. The "|" character is only recognized by the shell, not by sox. The "-c" tells the shell to run a single command, and passes the entire command as the single argument.

Executing terminal commands from java

I don't have a Linux system here to play with, but I'm pretty certain that the second command above is trying to compile Java files named "Test.java", "&&", "java" and "Test"; in other words the Runtime.exec() method treats arguments literally instead of applying shell interpretation.

You could probably get it to work with something along the lines of:

Process p = Runtime.getRuntime().exec(
new String[] { "sh", "-c", "javac Test.java && java Test" });

Executing linux command in java and store the output in variable

First, don't use Runtime.exec. Always use ProcessBuilder, which has much more reliable and predictable behavior.

Second, everything in your string is being passed as a single command, including the vertical bars. You are not passing it to a shell (like /bin/bash), so piping commands to one another won't work.

Third, you need to consume the command's output as it is running. If you call waitFor() and then try to read the output, it may work sometimes, but it will also fail much of the time. This behavior is highly operating system dependent, and can even vary among different Linux and Unix kernels and shells.

Finally, you don't need grep or wc. You have Java. Doing the same thing in Java is pretty easy (and probably easier than trying to invoke a shell so piping will work):

ProcessBuilder builder =
new ProcessBuilder("asterisk", "-rx", "ss7 linestat");
builder.inheritIO().redirectOutput(ProcessBuilder.Redirect.PIPE);
Process p = builder.start();

int freeE1s = 0;
try (BufferedReader buf =
new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String line;
while ((line = buf.readLine()) != null) {
if (line.contains("Idle")) { // No need for 'grep'
freeE1s++; // No need for 'wc'
}
}
}

p.waitFor();

System.out.println(freeE1s);

As of Java 8, you can make it even shorter:

ProcessBuilder builder =
new ProcessBuilder("asterisk", "-rx", "ss7 linestat");
builder.inheritIO().redirectOutput(ProcessBuilder.Redirect.PIPE);
Process p = builder.start();

long freeE1s;
try (BufferedReader buf =
new BufferedReader(new InputStreamReader(p.getInputStream()))) {
freeE1s = buf.lines().filter(line -> line.contains("Idle")).count();
}

p.waitFor();

System.out.println(freeE1s);

Executing a Linux command in Terminal from Java

I have had a hard time trying to get commands run using Runtime.exec() in the past. Anyways I have shifted to using ProcessBuilder as follows:

ProcessBuilder pbuilder = new ProcessBuilder("bash", "-c", <<your command as string>>);
File err = new File("err.txt");
try {
pbuilder.redirectError(err);
Process p = pbuilder.start();
p.waitFor();

} catch (Exception e)
{
//handle exceptions if any.
}

The stderr line is optional, for debugging purposes. I am sure that it could be directly printed out to console, but havn't checked on it yet. Will update my answer, once I find more.

You can check out the documentation page here.

PS: Also check if you have the necessary permissions to carry out the desired task.

How to run commands you can run on terminal in Java

The existing answers give you the information on how to solve your problem in code, but they don't give a reason why your code is not working.

When you execute a program on a shell, there's significant processing done by the shell, before the program is ever executed. Your command line

    String[] command = {"ag","startTimes conf.js >> pro.txt"};
ProcessBuilder builder = new ProcessBuilder(command);

assumes that the command ag is run with the single argument startTimes conf.js >> pro.txt - most likely not what you want to do. Let's go one step further: What if you wrote

    String[] command = {"ag","startTimes", "conf.js", ">>", "pro.txt"};
ProcessBuilder builder = new ProcessBuilder(command);

?

This would assume that the ag command knows about the >> parameter to redirect its output - and here is where the shell comes into play: The >> operator is an instruction to the shell, telling it what to do with the output from stdout of the process. The process ag, when started by the shell, never has an idea of this redirection and has no clue about >> and the target file name at all.

With this information, just use the code samples from any of the other answers. I won't copy them into mine for proper attribution.



Related Topics



Leave a reply



Submit