Use Process.getInputStream() to get an InputStream that represents the stdout of the newly created process.

Note that starting/running external processes from Java can be very tricky and has quite a few pitfalls.

They are described in this excellent article, which also describes ways around them.

Answer from Joachim Sauer on Stack Overflow
🌐
Coderanch
coderanch.com › t › 751548 › java › Execute-Linux-Command-Return-Output
Execute Linux Command and Return Output (Java in General forum at Coderanch)
May 9, 2022 - Incidentally, in Linux, an SMB shared file path is in the form "//hostname/sharename/dirname/dirname/filename". Even outside of Java, since backslashes are perilous to Unix-style users. Yes, there is a Java library for working with CIFS file sharing. And no, I don't recommend using Runtime.exec() to execute a series of commands and especially not with redirects.
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - try { // -- Linux -- // Run a shell command // Process process = Runtime.getRuntime().exec("ls /home/mkyong/"); // Run a shell script // Process process = Runtime.getRuntime().exec("path/to/hello.sh"); // -- Windows -- // Run a command //Process process = Runtime.getRuntime().exec("cmd /c dir C:\\Users\\mkyong"); //Run a bat file Process process = Runtime.getRuntime().exec( "cmd /c hello.bat", null, new File("C:\\Users\\mkyong\\")); StringBuilder output = new StringBuilder(); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line
🌐
GitHub
gist.github.com › 4283217
Executing a linux bash command from a java program and reading the response of it which spans multiple lines · GitHub
Executing a linux bash command from a java program and reading the response of it which spans multiple lines
Top answer
1 of 2
14

The primary reason why this doesn't work is that `$2` is not the same as `ls -1 | tail -1`, even when $2 is set to that string.

If your script accepts a literal string with a command to execute, you can use eval to do so.

I created a complete example. Please copy-paste it and verify that it works before you try applying any of it to your own code. Here's Test.java:

import java.io.*;

public class Test {
  public static void main(String[] args) throws Exception {
    String[] command = { "./myscript", "key", "ls -t | tail -n 1" };
    Process process = Runtime.getRuntime().exec(command);
    BufferedReader reader = new BufferedReader(new InputStreamReader(
        process.getInputStream()));
    String s;
    while ((s = reader.readLine()) != null) {
      System.out.println("Script output: " + s);
    }
  }
}

And myscript:

#!/bin/bash
key="$1"
value=$(eval "$2")
echo "The command  $2  evaluated to: $value"

Here's how we can run myscript separately:

$ ls -t | tail -n 1
Templates

$ ./myscript foo 'ls -t | tail -n 1'
The command  ls -t | tail -n 1  evaluated to: Templates

And here's the result of running the Java code:

$ javac Test.java && java Test
Script output: The command  ls -t | tail -n 1  evaluated to: Templates 
2 of 2
0

As other posters pointed out already, the sub-process is not started in a shell, so the she-bang is not interpreted.

I got your example to work by explicitly starting the evaluation of the second parameter in a shell in jj.sh:

value=`sh -c "$2"` 

Not nice, but works.

Other option may be to start the script in a shell explicitly, emulating the sh-bang:

String[] cmd = { "/bin/sh", "jj.sh" , key,value};
🌐
CodeJava
codejava.net › java-se › file-io › execute-operating-system-commands-using-runtime-exec-methods
How to Execute Operating System Commands in Java
July 27, 2019 - Throughout this tutorial, you will learn how to execute a native command from within a Java program, including sending inputs to and getting outputs from the command.Basically, to execute a system command, pass the command string to the exec() method of the Runtime class.
🌐
Baeldung
baeldung.com › home › java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - @Test public void givenProcessBuilder_whenStartingPipeline_thenSuccess() throws IOException, InterruptedException { List<ProcessBuilder> builders = Arrays.asList( new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), new ProcessBuilder("wc", "-l")); List<Process> processes = ProcessBuilder.startPipeline(builders); Process last = processes.get(processes.size() - 1); List<String> output = readOutput(last.getInputStream()); assertThat("Results should not be empty", output, is(not(empty()))); } In the above example, we’re searching for all the java files inside the src directory and piping the results into another process to count them. To learn about other improvements made to the Process API in Java 9, check out our great article on Java 9 Process API Improvements. As we’ve seen in this quick tutorial, we can execute a shell command in Java in two distinct ways.
Find elsewhere
Top answer
1 of 10
64

You can use java.lang.Runtime.exec to run simple code. This gives you back a Process and you can read its standard output directly without having to temporarily store the output on disk.

For example, here's a complete program that will showcase how to do it:

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

public class testprog {
    public static void main(String args[]) {
        String s;
        Process p;
        try {
            p = Runtime.getRuntime().exec("ls -aF");
            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) {}
    }
}

When compiled and run, it outputs:

line: ./
line: ../
line: .classpath*
line: .project*
line: bin/
line: src/
exit: 0

as expected.

You can also get the error stream for the process standard error, and output stream for the process standard input, confusingly enough. In this context, the input and output are reversed since it's input from the process to this one (i.e., the standard output of the process).

If you want to merge the process standard output and error from Java (as opposed to using 2>&1 in the actual command), you should look into ProcessBuilder.

2 of 10
27

You can also write a shell script file and invoke that file from the java code. as shown below

{
   Process proc = Runtime.getRuntime().exec("./your_script.sh");                        
   proc.waitFor();
}

Write the linux commands in the script file, once the execution is over you can read the diff file in Java.

The advantage with this approach is you can change the commands with out changing java code.

🌐
GeeksforGeeks
geeksforgeeks.org › java › how-to-execute-native-shell-commands-from-java-program
How to Execute Native Shell Commands from Java Program? - GeeksforGeeks
March 3, 2021 - For example, a Java program running specifically Linux shell commands cannot run as-is on a Windows machine mainly because Windows has a different folder structure and shell commands. ... The first three examples will look at implementing the ProcessBuilder class to run shell commands in Java. The following example is for the RunTime class. Example 1: Loss of portability. This example shows what happens if we execute a Java program meant for the Linux/Unix operating system on a Windows operating system.
🌐
Alvin Alexander
alvinalexander.com › java › java-exec-system-command-pipeline-pipe
Java exec: How to execute a system command pipeline in Java | alvinalexander.com
Jumping right in, let's imagine that you want to run the following Unix/Linux command from your Java application: ... package com.devdaily.system; import java.io.IOException; import java.util.*; public class ProcessBuilderExample { public static void main(String[] args) throws IOException, InterruptedException { // you need a shell to execute a command pipeline List<String> commands = new ArrayList<String>(); commands.add("/bin/sh"); commands.add("-c"); commands.add("ls -l /var/tmp | grep foo"); SystemCommandExecutor commandExecutor = new SystemCommandExecutor(commands); int result = commandExecutor.executeCommand(); StringBuilder stdout = commandExecutor.getStandardOutputFromCommand(); StringBuilder stderr = commandExecutor.getStandardErrorFromCommand(); System.out.println("STDOUT"); System.out.println(stdout); System.out.println("STDERR"); System.out.println(stderr); } }
🌐
Java2s
java2s.com › example › java › native-os › execute-shell-command-and-get-output.html
execute Shell Command And Get Output - Java Native OS
import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class Main{ public static void main(String[] argv) throws Exception{ String command = "java2s.com"; System.out.println(executeCommandAndGetOutput(command)); }//from www . j av a2s .c o m public static String executeCommandAndGetOutput(String command) throws Exception { Process proc = createAndExecuteProcess(command); logForProc(proc); return getOuputMessageOfCommand(proc.getInputStream()); } private static Process createAndExecuteProcess(String co
🌐
Crunchify
crunchify.com › macos tutorials › how to run windows, linux, macos terminal commands in java and return complete result
How to Run Windows, Linux, macOS terminal commands in Java and return complete Result • Crunchify
February 26, 2019 - package crunchify.com.tutorials; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; /** * @author Crunchify.com * Execute Linux commands using Java. We are executing mkdir, ls -ltra and ping in this tutorial */ public class CrunchifyCommandJava { public printOutput getStreamWrapper(InputStream is, String type) { return new printOutput(is, type); } public static void main(String[] args) { Runtime rt = Runtime.getRuntime(); CrunchifyCommandJava rte = new CrunchifyCommandJava(); printOutput errorReported, outputMessage; try { P
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - The Runtime class in Java is a high-level class, present in every single Java application. Through it, the application itself communicates with the environment it's in. By extracting the runtime associated with our application via the getRuntime() method, we can use the exec() method to execute ...
🌐
CopyProgramming
copyprogramming.com › howto › java-run-command-and-get-output-java
Java: Executing Java Commands and Retrieving Output in Java
April 25, 2023 - To ensure successful output reading of a command while it's running, consumption of the output is necessary. Simply calling waitFor() and attempting to read the output may produce intermittent results depending on the operating system, as well as the various Linux and Unix kernels and shells. In conclusion, Java can replace the need for both grep and wc .
🌐
Blogger
javarevisited.blogspot.com › 2011 › 02 › how-to-execute-native-shell-commands.html
How to Execute Native Shell commands from Java Program? Example
Anyway, if you have no choice and you want to execute native commands from Java then it's good to know that how we can do it, many of you probably know this but for those who don't know and have never done it, we will see through an example. Suppose you want to execute the "ls" command in Linux which lists down all the files and directories in a folder and you want to do it using Java.
Top answer
1 of 14
323

Here is the way to go:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-get t"};
Process proc = rt.exec(commands);

BufferedReader stdInput = new BufferedReader(new 
     InputStreamReader(proc.getInputStream()));

BufferedReader stdError = new BufferedReader(new 
     InputStreamReader(proc.getErrorStream()));

// Read the output from the command
System.out.println("Here is the standard output of the command:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
    System.out.println(s);
}

// Read any errors from the attempted command
System.out.println("Here is the standard error of the command (if any):\n");
while ((s = stdError.readLine()) != null) {
    System.out.println(s);
}

Read the Javadoc for more details here. ProcessBuilder would be a good choice to use.

2 of 14
88

A quicker way is this:

public static String execCmd(String cmd) throws java.io.IOException {
    java.util.Scanner s = new java.util.Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A");
    return s.hasNext() ? s.next() : "";
}

Which is basically a condensed version of this:

public static String execCmd(String cmd) throws java.io.IOException {
    Process proc = Runtime.getRuntime().exec(cmd);
    java.io.InputStream is = proc.getInputStream();
    java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A");
    String val = "";
    if (s.hasNext()) {
        val = s.next();
    }
    else {
        val = "";
    }
    return val;
}

I know this question is old but I am posting this answer because I think this may be quicker.

Edit (For Java 7 and above)

Need to close Streams and Scanners. Using AutoCloseable for neat code:

public static String execCmd(String cmd) {
    String result = null;
    try (InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
            Scanner s = new Scanner(inputStream).useDelimiter("\\A")) {
        result = s.hasNext() ? s.next() : null;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return result;
}
🌐
GitHub
gist.github.com › padcom › a5831bea701ef08ce944
Running a process and reading its output in Java · GitHub
Running a process and reading its output in Java. GitHub Gist: instantly share code, notes, and snippets.
🌐
Medium
beknazarsuranchiyev.medium.com › run-terminal-commands-from-java-da4be2b1dc09
Run terminal commands from Java. In this article, we will discuss how to… | by Beknazar | Medium
April 24, 2022 - It’s quite helpful to know how to run the operating system processes via Java code. The ProcessBuilder class is used to build Process object. We specify the commands and other configurations in the ProcessBuilder. We work on actual execution with Process instance. For example to get the status code from the process, to get its id, to see the output, to wait, and to kill the process.
🌐
ExtraVM
thishosting.rocks › how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - The exec() method is for executing commands directly or running .bat/.sh files. try { // -- Linux -- // Run a shell command // Process process = Runtime.getRuntime().exec("ls /home/mkyong/"); // Run a shell script // Process process = ...