You should really look at Process Builder. It is really built for this kind of thing.

ProcessBuilder pb = new ProcessBuilder("myshellScript.sh", "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"));
 Process p = pb.start();
Answer from Milhous on Stack Overflow
๐ŸŒ
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.
๐ŸŒ
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
public static void main(String[] args) { Process p; try { String[] cmd = { "sh", "C://Users//E5601972//Documents//sample.sh"}; p = Runtime.getRuntime().exec(cmd); p.waitFor(); BufferedReader reader=new BufferedReader(new InputStreamReader( p.getInputStream())); String line; while((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } ReplyDelete ... You are trying to run shell script on a Windows system!
Discussions

can java run shell script on a windows system?
Java doesn't "use Linux". The Java platform is available for many operating systems, two of which are Microsoft Windows and Linux. This doesn't mean that Java bestows any OS specific capabilities from one of those platforms on another of those platforms. Java merely allows you to execute a process available on the OS in which the Java environment is running. Additionally, as is the unix way, you'd need more than a Java implementation of bash to run the scripts on Windows. You'd also need implementations of all of the commands used in the script (as it's highly unlikely your scripts are entirely comprised of bash built-in features). More on reddit.com
๐ŸŒ r/learnjava
4
2
March 21, 2020
bash - How to execute shell script on windows using JAVA - Stack Overflow
Im trying to execute shell script in JAVA on windows machine . below is the code ยท public static void main(String[] args) throws IOException, InterruptedException { // TODO Auto-generated method stub String abc; String abc1; Process proc = Runtime.getRuntime().exec("bash.exe C:\\Users\\ab... More on stackoverflow.com
๐ŸŒ stackoverflow.com
windows - Java code to execute a .sh file - Stack Overflow
It's not possible to run a Unix shell script natively in Windows, which is what you're trying to do -- you'll need to convert (not just rename) that Unix shell script to a Windows batch file (with a .bat or .cmd filename extension/suffix). Which exception is being thrown? Which version of Java are ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 17, 2011
Java program to run shell commands from a windows machine - Stack Overflow
I am trying to run a Java program to shell out commands on a remote (Linux) machine. I can get the putty.exe to run and then connect to the machine using SSH keys. But am not able to run the actual More on stackoverflow.com
๐ŸŒ stackoverflow.com
March 24, 2017
๐ŸŒ
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...

๐ŸŒ
Stack Abuse
stackabuse.com โ€บ executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - In this article, we'll take a look at how we can leverage the Runtime and ProcessBuilder classes to execute shell commands and scripts with Java.
๐ŸŒ
Kevin Boone
kevinboone.me โ€บ exec.html
How to run a shell script from a Java application - Kevin Boone
The Java documentation does not provide a lot of help, even though the exec() method has had developers banging their heads on their desks for as long as Java has existed. Runtime.exec() is problematic for reasons that have nothing to do with running shell scripts โ€” scripts simply add a bunch of other pain points to an already painful experience. This article describes in detail why exec() and its related API methods are so difficult to use properly, and outlines what I hope is a reasonably robust implementation.
๐ŸŒ
DEV Community
dev.to โ€บ coder4_life โ€บ how-to-run-shell-scripts-in-java-4cbd
How to run shell scripts in Java - DEV Community
December 6, 2021 - Running shell scripts from inside Java code using ProcessBuilder in a thread. This solution works on Windows (.bat file) and Unix (.sh file) - running example in both environments in video.
๐ŸŒ
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 - This example shows how to run a simple Windows shell command. We use a list to build commands and then execute them using the "start" method of the ProcessBuilder class.
Find elsewhere
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());
Top answer
1 of 5
3

To execute a .sh script on Windows, you would have to have a suitable command interpreter installed. For example, you could install the Cygwin environment on your Windows box and use it's bash interpreter.

However, Windows is not Linux even with Cygwin. Some scripts will not port from one environment to the other without alterations. If I had a problem executing a script via Java in Linux environment, I would prefer to debug the issue in that environment.

Remember, you could start your Java process on Linux in debug mode and attach your IDE debugger in Windows to that remote process.

2 of 5
3

Thanks everybody for your responses. I found a solution to the problem. For this kind of situation we need to bind my Windows machine to Linux system. Here is the code that worked:

Copypublic String executeSHFile(String Username, String Password,String  Hostname)
    {
        String hostname = Hostname;
        String username = Username;
        String password = Password;
        try{
            Connection conn = new Connection(hostname);
               conn.connect();
               boolean isAuthenticated = conn.authenticateWithPassword(username, password);
               if (isAuthenticated == false)
                throw new IOException("Authentication failed.");
               Session sess = conn.openSession();
              sess.execCommand("sh //full path/file name.sh");

               System.out.println("Here is some information about the remote host:");
               InputStream stdout = new StreamGobbler(sess.getStdout());
               BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
               while (true)
                {
                    String line = br.readLine();
                    if (line == null)
                        break;
                    current_time=line;
                    System.out.println(line);
                }

               System.out.println("ExitCode: " + sess.getExitStatus());
               /* Close this session */

                sess.close();

                /* Close the connection */

                conn.close();
        }catch(IOException e)
        {
            e.printStackTrace(System.err);
            System.exit(2);
        }finally{

        }
}

Thank you.

๐ŸŒ
YouTube
youtube.com โ€บ watch
How to run shell scripts in Java - YouTube
Running shell scripts from inside Java code using ProcessBuilder in a thread. This solution works on Windows (.bat file) and Unix (.sh file) - running exampl...
Published ย  December 6, 2021
๐ŸŒ
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 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. I could not make the Linux commands run from Java which is on Windows using this code.
๐ŸŒ
YouTube
youtube.com โ€บ watch
How to execute a shell script from Java in Eclipse - YouTube
How to execute a shell script from Java in Eclipse1) A java project.2) Create a simple shell script.3) Call shell script from java program using ProcessBuild...
Published ย  May 16, 2020
๐ŸŒ
ExtraVM
thishosting.rocks โ€บ how-to-execute-a-shell-command-using-java
How To Execute a Shell Command Using Java
May 19, 2021 - Runtime.exec() is a simple high-level class, not customizable at the moment but available in every Java application. It gives the possibility for the application to communicate within its environment. 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 = Runtime.getRuntime().exec("path/to/hello.sh"); // -- Windows -- // Run a command //Process process = Runtime.getRuntime().exec("cmd /c dir C:\\Users\\mkyong"); //Ru
๐ŸŒ
Quora
quora.com โ€บ How-do-I-run-a-shell-script-from-Java-code
How to run a shell script from Java code - Quora
Answer (1 of 7): Here are multiple ways already suggested in stackoverflow and both are good: How to run Unix shell script from java code? Run shell script from Java Synchronously
๐ŸŒ
Edureka Community
edureka.co โ€บ home โ€บ community โ€บ categories โ€บ java โ€บ how to run unix shell script from java code
How to run Unix shell script from Java code | Edureka Community
October 26, 2018 - It is quite simple to run a Unix command from Java. Runtime.getRuntime().exec(myCommand); But ... to run a shell script from within Java code?
๐ŸŒ
javathinking
javathinking.com โ€บ blog โ€บ how-to-run-unix-shell-script-from-java-code
How to Run a Unix Shell Script from Java Code: Step-by-Step Guide & Best Practices โ€” javathinking.com
While Java provides APIs to execute ... walk you through step-by-step methods to run shell scripts from Java, including best practices to avoid pitfalls and ensure robustness. ... Unix-like Environment: Linux, macOS, or WSL (Windows Subsystem for Linux)....