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.

Answer from paxdiablo on Stack Overflow
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.

🌐
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 - Java's Process can only execute one single command. Ron's solution works because it removes two of the commands. Tim Cooke's suggestion also would have worked - use a script. Because that would be a single command again to Process. SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6 - OCEJPAD 6 How To Ask Questions How To Answer Questions ... Ron McLeod wrote:You should be able to just check the exit value from grep to determine if a match was found.
🌐
JavaPointers
javapointers.com › java › java-core › how-to-run-a-command-using-java-in-linux-or-windows
How To Run a Command using Java in Linux or Windows - JavaPointers
May 24, 2020 - Below is a sample code on how to execute or run a command using Java. First, we create a new ProcessBuilder and add the command. Next, we start the process using the start() method.
🌐
YouTube
youtube.com › sagar s (vishal)
How to execute linux commands in Java - YouTube
AboutPressCopyrightContact usCreatorsAdvertiseDevelopersTermsPrivacyPolicy & SafetyHow YouTube worksTest new features · © 2024 Google LLC · YouTube, a Google company
Published   July 27, 2016
Views   14K
🌐
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 - In this article, we will discuss how to run terminal commands from Java code. We can execute specific commands from the terminal to execute processes in an operating system. The most used ones are in Linux-based operating systems.
🌐
Baeldung
baeldung.com › home › java › core java › how to run a shell command in java
How to Run a Shell Command in Java | Baeldung
January 8, 2024 - Instead, on Linux and macOS, shell commands are run using /bin/sh. For compatibility on these different machines, we can programmatically append cmd.exe if on a Windows machine or /bin/sh otherwise. For instance, we can check if the machine where the code is running is a Windows machine by reading the “os.name” property from the System class:
🌐
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
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - c:mysql then the prompt changes to: mysql> now in this we type sql commands. Can we achieve/automate this with java? ... The article would be even better with a note on how to run a shell file sitting in the resources directory. Thanks for the jump start anyway ! ... I really like your articles on Java. For this one i guess i could not do as mentioned. I googled and figured out that you need to first connect to the linux box from java and then you can execute shell commands.
Find elsewhere
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - public Process exec(String command, String[] envp, File dir) - Executes the command, with the specified environment variables, from within the dir directory.
🌐
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 ...
🌐
CodingTechRoom
codingtechroom.com › question › -execute-linux-command-java
How to Execute Linux Commands from Java: A Comprehensive Guide - CodingTechRoom
Learn how to run Linux commands within Java applications. Step-by-step guide with code examples and common troubleshooting tips.
🌐
DaniWeb
daniweb.com › programming › software-development › threads › 363596 › run-a-linux-command-using-java
Run a linux command using java | DaniWeb
May 10, 2011 - ProcessBuilder pb = new ProcessBuilder("sh", "-c", "sh /usr/bin/sshlogin.sh '192.168.0.37|danga|dan1ga|java -jar /shared/smsfiles/coin/MySSH.jar'"); pb.redirectErrorStream(true); Process p = pb.start(); // read p.getInputStream(), waitFor(), check exit value · Quote any argument that must keep literal | so the shell does not split it. Be careful: building command strings from untrusted input risks shell injection.
🌐
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 = ...
🌐
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 - My Favorite Linux Commands – List of Top 25+ Basic Linux Commands and Cheat Sheet · How to Install Apache Web Server, PHP, Perl on Mac OS X Yosemite ... Can we run kubectl commands through java. Ex: kubectl version, kubectl get pods ... Hi Gourav. Sure. You could without any issue. Theoretically you could run any commands as far as binaries are install on VM/host you are running it. ... Hello, really god tutorial. But it does not works with external tools like the s3cmd from Amazon.
Top answer
1 of 3
110

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"});
2 of 3
35

Use ProcessBuilder to separate commands and arguments instead of spaces. This should work regardless of shell used:

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(final String[] args) throws IOException, InterruptedException {
        //Build command 
        List<String> commands = new ArrayList<String>();
        commands.add("/bin/cat");
        //Add arguments
        commands.add("/home/narek/pk.txt");
        System.out.println(commands);

        //Run macro on target
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.directory(new File("/home/narek"));
        pb.redirectErrorStream(true);
        Process process = pb.start();

        //Read output
        StringBuilder out = new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null, previous = null;
        while ((line = br.readLine()) != null)
            if (!line.equals(previous)) {
                previous = line;
                out.append(line).append('\n');
                System.out.println(line);
            }

        //Check result
        if (process.waitFor() == 0) {
            System.out.println("Success!");
            System.exit(0);
        }

        //Abnormal termination: Log command parameters and output and throw ExecutionException
        System.err.println(commands);
        System.err.println(out.toString());
        System.exit(1);
    }
}
🌐
Princeton CS
introcs.cs.princeton.edu › java › 15inout › linux-cmd.html
Java and the Linux Command Line
August 14, 2019 - In case you don't know, type the following command: [wayne] ~> echo $SHELL Your shell will likely be bash, tcsh, sh, or ksh. To make sure Linux can find the Java compiler and interpreter, edit your shell login file according to the shell you are using. Bash. If you are using the bash shell, ...
🌐
LinuxForDevices
linuxfordevices.com › home › how to run a command-line java program on linux?
How to Run a Command-Line Java Program on Linux? - LinuxForDevices
July 19, 2021 - To run the Java program, execute: ... Notice that we haven’t used any file extension while running a Java program using the java command. This is because the Java command can identify the compiled Java files and does not need the .java extension to be added. You can easily write, compile, and run a Java program from ...
🌐
Iditect
iditect.com › faq › java › how-to-run-linux-commands-in-java.html
How to run Linux commands in Java?
You can also execute Linux commands using the Runtime.getRuntime().exec() method, although this approach is less flexible and may not capture the command's output as easily as ProcessBuilder. Here's an example: import java.io.BufferedReader; import java.io.IOException; import java.io.Input...