How to Invoke a Linux Shell Command from Java

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

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.

How to execute shell command in Java?

I am not sure if you are asking about Shell command execution, or ipconfig in general.

If the first is the case here: Yep, you can use Runtime.getRuntime.exec().
Related Answers (In Stackoverflow):

  1. Executing shell commands from Java
  2. Want to invoke a linux shell command from Java

Moreover to the answers provided there, here is my example on how you do it with "host -t a" command for DNS lookups. I would generally recommend to read through the list you get and append them in an String for logging purposes.

p = Runtime.getRuntime().exec("host -t a " + domain);
p.waitFor();

BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));

String line = "";
while ((line = reader.readLine())!= null) {
sb.append(line + "\n");
}

The other solution which herausuggested was to use ProcessBuilderand execute the command from there. For this you need to use Java SE 7 upwards. Here is an example that starts a process with a modified working directory and environment, and redirects standard output and error to be appended to a log file:

 ProcessBuilder pb =
new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory(new File("myDir"));
File log = new File("log");
pb.redirectErrorStream(true);
pb.redirectOutput(Redirect.appendTo(log));
Process p = pb.start();
assert pb.redirectInput() == Redirect.PIPE;
assert pb.redirectOutput().file() == log;
assert p.getInputStream().read() == -1;

If you wanna know more about ProcessBuilder, read through the documentation: Oracle Documentation on Class ProcessBuilder



Related Topics



Leave a reply



Submit