๐ŸŒ
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 - In this article, weโ€™ll learn how to execute a shell command from Java applications. First, weโ€™ll use the .exec() method the Runtime class provides. Then, weโ€™ll learn about ProcessBuilder, which is more customizable. Shell commands are OS-dependent as their behavior differs across systems. So, before we create any Process to run our shell command in, we need to be aware of the operating system on which our JVM is running. Additionally, on Windows, the shell is commonly referred to as cmd.exe.
๐ŸŒ
GitHub
github.com โ€บ Dualcon โ€บ Java-ShellCommand
GitHub - Dualcon/Java-ShellCommand: Java - How to execute shell commands on Windows or Mac OS ยท GitHub
In Java, you can use Runtime.getRuntime().exec to execute external shell command. Here is a classical example to execute the ping command and print out its output. ... public static void main(String[] args) { String domainName = "google.com"; // Execute the command in windows String command = "ping -n 3 " + domainName...
Author ย  Dualcon
Discussions

How to invoke a Linux shell command from Java - Stack Overflow
I am trying to execute some Linux commands from Java using redirection (>&) and pipes (|). How can Java invoke csh or bash commands? ... But it's not compatible with redirections or pipes. ... i can understand the question for other commands, but for cat: why the hell don't you just read in the file? ... Everyone gets this wrong first time - Java's exec() does not use the underlying system's shell ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to execute shell command in Java? - Stack Overflow
I am not sure if you are asking about Shell command execution, or ipconfig in general. More on stackoverflow.com
๐ŸŒ stackoverflow.com
bash - How to execute shell script on windows using JAVA - Stack Overflow
Im trying to execute shell script in JAVA on windows machine . More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to run a shell command in the calling (current) shell with Java - Stack Overflow
You won't be able to run commands that affect the current invoking shell, only to run command line bash/cmd as sub-process from Java and send them commands as follows. More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - The addition of cmd /c before a command such as dir is worth noting. Since I'm working on Windows, this opens up the cmd and /c carries out the subsequent command.
๐ŸŒ
Mkyong
mkyong.com โ€บ home โ€บ java โ€บ how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - I used the same (similar) code for my ShellWrapper. When I use commands like echo it works fine, but when I use commands like cat it returns an empty Stringโ€ฆ. ... As a good practice, I wouldnโ€™t catch Exception e. Just mention the two that need to be dealt with (IOException, InterruptedException) . ... I am trying to convert avro to json file through java, But it is not working String output = obj.executeCommand(โ€œjava -jar /Users/xyz/Desktop/1server/jboss-as-7.1.1.Final/standalone/deployments/Command.war/WEB-INF/lib/avro-tools-1.7.7.jar tojson /Users/xyz/Desktop/avro/4.avro > /Users/xyz/Desktop/avro/D8EC9CC2A3E049648AFD4309B29D2A0F/4.jsonโ€); But this is not working through java file,
๐ŸŒ
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 - We use a list to build commands and then execute them using the "start" method of the ProcessBuilder class. The program runs the command to find the chrome browser processes from the tasklist running in the machine. ... // Run a simple Windows shell command import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class ShellCommandRunner { public static void main(String[] args) { ProcessBuilder processBuilder = new ProcessBuilder(); List<String> builderList = new ArrayList<>(); // add the list of comm
๐ŸŒ
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 = ...
๐ŸŒ
Kevin Boone
kevinboone.me โ€บ exec.html
How to run a shell script from a Java application - Kevin Boone
Running a shell script from a Java program using Runtime.exec() appears simple. In practice, there are many pitfalls. This article describes how to avoid at least some of them.
Top answer
1 of 3
111

exec does not execute a command in your shell

try

CopyProcess 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

CopyProcess 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:

Copyimport 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);
    }
}
Find elsewhere
๐ŸŒ
Admfactory
admfactory.com โ€บ home โ€บ how to execute shell command from java
How to execute shell command from Java | ADMFactory
June 20, 2018 - Here is a simple code on how to execute a shell command from Java. As a sample command, it is used the ping command and the example was tested using Windows 10.
Top answer
1 of 1
15

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

Top answer
1 of 3
5

Make sure bash.exe is in PATH as Charles Duffy said. Having bash installed without that being the case, is, after all, not much use. When that's the case and your script is in the current directory, the following is equivalent to your code:

public class Test {
    public static void main(String[] args) throws Exception {
        String[] command = { "bash", "test.sh" };
        ProcessBuilder pb = new ProcessBuilder(command).inheritIO();
        Process p = pb.start();
        p.waitFor();
        System.out.println(p.exitValue());
    }
}
2 of 3
1

Note: You should use ProcessBuilder to launch as it provides better control over I/O streams, and the Runtime.exec call you use is deprecated. However the outcome would be the same in your case.

The issue here is that bash on Windows is expecting a Linux style pathname, and you are passing in Windows OS pathname.

Your Path environment for bash.exe is correct because you don't get IOException : Cannot run program "bash.exe": CreateProcess error=2, The system cannot find the file specified.

Thus bash.exe has run, but it reports exit code 127 which means Command not found, or PATH error. To fix you need to form valid GNU/Linux pathname to the script. If you are using WSL the C drive is mapped as "/mnt/c" so you need to run the translated path:

String[] cmd = new String[]{ "bash.exe", "/mnt/c/Users/abc/Downloads/test.sh" };

// Using "bash" above should also work if "bash.exe" is in the Path and PATHEXT contains ".EXE"
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
p.getInputStream().transferTo(System.out);
System.out.println(p.waitFor());

You could avoid the OS pathname translation by using a relative path to the script and run from it's directory:

File exe = new File("C:\\Users\\abc\\Downloads\\test.sh");
// Set up relative path for the script
String[] cmd = new String[]{"bash", exe.getName()};

ProcessBuilder pb = new ProcessBuilder(cmd).redirectErrorStream(true);
// Run from the directory of the script:
pb.directory(exe.getParentFile());
Process p = pb.start();
p.getInputStream().transferTo(System.out);
System.out.println(p.waitFor());
๐ŸŒ
Netjstech
netjstech.com โ€บ 2016 โ€บ 10 โ€บ how-to-run-shell-script-from-java-program.html
How to Run a Shell Script From Java Program | Tech Tutorials
You can't just rum a sh file from windows command line. Delete ... If you are using Windows replace "sh" with "cmd". The terminal of is "powershell" or "cmd". "sh", "/bin/bash", "/usr/bin/python" for other kinds of scripts.ReplyDelete ... This method works fine when I try to execute on local.
๐ŸŒ
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 - We are going to discuss ProcessBuilder.java and Process.java files. Ok, letโ€™s see one code that can execute commands from the terminal: The above code executes ls commands to list files and directories on my desktop. You can modify the path of the file to point to your desktop or any folder and try running other commands. If you are on a Windows machine of course you have to run the command that works on the Windows command prompt.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ can java run shell script on a windows system?
r/learnjava on Reddit: can java run shell script on a windows system?
March 21, 2020 -

https://www.baeldung.com/run-shell-command-in-java

so, java uses linux, and as a way to cut down on coding projects time to completion, I was wondering, if there is a bash sdk or something similar for java that can be wrapped into a jar and used to make an executable, that way a windows computer can run it, and a linux computer can as well..

I want to be able to run code from other programming languages that utilize terminal, but... I don't expect end users to be able to set up bash or even work terminal, I could write batch scripts and have two different downloads or I could have the code ping for the OS of the system and send the user to one of the two, but if possible this would be really helpful to know going forward...

just wondering if anyone knows of a package that can be wrapped in for bash integration for your jar so the scripts run within the jvm and not called by it...

๐ŸŒ
Blogger
javarevisited.blogspot.com โ€บ 2011 โ€บ 02 โ€บ how-to-execute-native-shell-commands.html
How to Execute Native Shell commands from Java Program? Example
In Java we have a class called "java.lang.Runtime" which is used to interact with the Runtime system has the facility to execute any shell command using method exec().
๐ŸŒ
DZone
dzone.com โ€บ coding โ€บ languages โ€บ execute shell command from java
Execute Shell Command From Java
August 14, 2008 - String cmd = "ls -al"; Runtime run = Runtime.getRuntime(); Process pr = run.exec(cmd); pr.waitFor(); BufferedReader buf = new BufferedReader(new...
๐ŸŒ
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 - For example, the following statements execute a Windows command to list content of the Program Files directory: String commandArray[] = {"cmd", "/c", "dir", "C:\\Program Files"}; Process process = Runtime.getRuntime().exec(commandArray);For other exec() methods, consult the relevant Javadoc which is listed below.