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:
๐ŸŒ
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 - The challenge from java is getting the same command to run. The snippet of my code that handles this is as follows, though it does not run as expected: public void runCron(String job) { System.out.println("Inside runCron..."); Runtime r = Runtime.getRuntime(); Process p = null; String opt1 = "sh", opt2 = "/usr/bin/sshlogin.sh", opt3 = "192.168.0.37|danga|dan1ga|java" ,opt4= "-jar",opt5="/shared/smsfiles/coin/MySSH.jar"; String [] commands = {opt1, opt2, opt3, opt4, opt5}; if(job != null) { try { p = r.exec(commands); BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream())); String str = ""; while ((str = br.readLine()) != null) { System.out.println(str); } br.close(); p.waitFor(); } catch (Exception e) { System.out.println("Exception "+e.getMessage()); System.err.println("Exception "+e.getMessage()); } } }//runCron
๐ŸŒ
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...