How to run unix/shell command in java like chmod, mkdir, grep or any unix commands

Running shell command in Java

In this tutorial, We are going to learn how to run shell commands from java such as chmod, mkdir, grep files.

run-shell-command-in-java

Find operating system:

Before running the command, we must know the operating system where the application is running.

By calling System.getProperty("os.name") method, we will get the OS name.

private String OS = System.getProperty("os.name").toLowerCase();

This statement, may return the following operating system names.

Linux, Windows, SunOS, Mac OS, HP-UX and AIX


if (isWindows) {
// execure windows command
Runtime.getRuntime().exec("cmd.exe /c dir C://");
} else {
// for unix commands
Runtime.getRuntime().exec("sh -c ls /home/java_w3schools");

Runtime.getRuntime():

Runtime class has a exec(String command) method that Executes the specified string command in a separate process.

Before invoking this method, we must ensure that running program on correct OS.

chmod command execution:

Runtime.getRuntime().exec("sh -c chmod -R 777 /home/java_w3schools/start.sh");

Changing the file permissions to read/write/execute to all users.

mkdir command execution:

Runtime.getRuntime().exec("sh -c mkdir -p /home/java_w3schools/java/posts);

Creates folders recursively

grep command execution:

Runtime.getRuntime().exec("sh -c grep -i 'exception' /home/java_w3schools/java/server.log);

Print all the lines which is having exception word ignoring case in server.log

ProcessBuilder:


This class is used to create operating system processes. command() method to add the commands to the process builder and need to invoke the start() method to start a new process on the underlying operating system.

Example to ping using ProcessBuilder on Unix:

ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("sh", "-c", "ping -n 3 google.com");
Process process = processBuilder.start();

Output:

Pinging google.com [216.58.200.142] with 32 bytes of data:
Reply from 216.58.200.142: bytes=32 time=11ms TTL=51
Reply from 216.58.200.142: bytes=32 time=12ms TTL=51
Reply from 216.58.200.142: bytes=32 time=10ms TTL=51

Ping statistics for 216.58.200.142:
Packets: Sent = 3, Received = 3, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 10ms, Maximum = 12ms, Average = 11ms

chmod command:

processBuilder.command("sh", "-c", "chmod -R 777 /home/java_w3schools/start.sh");

mkdir command:

processBuilder.command("sh", "-c", "mkdir -p /home/java_w3schools/java/posts");

grep command:

processBuilder.command("sh", "-c", "grep -i 'exception' /home/java_w3schools/java/server.log");

Conclusion:

Today, we saw the guide to how to two ways of running a shell command in Java, both on Windows as well as on UNIX running example commands such as chmod, mkdir, grep etc.


0 Comments