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
🌐
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,
🌐
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 - Process process; if (isWindows) { process = Runtime.getRuntime() .exec(String.format("cmd.exe /c dir %s", homeDirectory)); } else { process = Runtime.getRuntime() .exec(String.format("/bin/sh -c ls %s", homeDirectory)); } StreamGobbler streamGobbler = new StreamGobbler(process.getInputStream(), System.out::println); Future<?> future = executorService.submit(streamGobbler); int exitCode = process.waitFor(); assertDoesNotThrow(() -> future.get(10, TimeUnit.SECONDS)); assertEquals(0, exitCode); Here, we created a new sub-process with .newSingleThreadExecutor() and then used .submit() to run our Process containing the shell commands.
🌐
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
If you have a shell script say test.sh then you can run it from a Java program using RunTime class or ProcessBuilder (Note ProcessBuilder is added in Java 5).
🌐
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.
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - 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 commands directly or run .bat/.sh files. The exec() method offers a few overloaded variations: ...
Find elsewhere
🌐
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 = ...
🌐
Coderanch
coderanch.com › t › 709609 › java › Executing-shell-script-java
Executing shell script in java (Java in General forum at Coderanch)
May 10, 2019 - But do you give the name and password as part of the command: $ <yourscript> some_user some_password Or does the script prompt for it: $ <yourscript> Please enter your username: some_user Please enter your password: some_password ? Finally, what does your code to execute and monitor the script currently look like? ... So I have a script like this: test.sh echo "hello login" read user read pw And the Java code above ^^ when I execute this script nothing happens it's like frozen
🌐
Coderanch
coderanch.com › t › 379834 › java › executing-shell-script-java
executing shell script from java (Java in General forum at Coderanch)
October 10, 2016 - Read from child.inputStream() -- which is the shell's stdout -- or child.errorStream() -- which is stderr. String file_location = "/users/temp/rams"; String file_location1 = "/users/temp/Test.java"; String a_mib_name = "Test269.java"; Runtime rtime = Runtime.getRuntime(); Process child = rtime.exec("/bin/bash"); child.getOutputStream().write("cd " + file_location); System.out.println("cd " + file_location); child.getOutputStream().write("ln -s " + file_location1 + " " + a_mib_name); child.getOutputStream().flush(); System.out.println("inside script"); cd and softlink commands are not working...
🌐
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
🌐
GitHub
gist.github.com › simonwoo › c21811eddf0392034946
execute a shell script from java.md · GitHub
Clone this repository at &lt;script src=&quot;https://gist.github.com/simonwoo/c21811eddf0392034946.js&quot;&gt;&lt;/script&gt; Save simonwoo/c21811eddf0392034946 to your computer and use it in GitHub Desktop. ... /** * execute shell script */ private static void executeScript() { try { String bash = "/bin/bash"; String script = "script.sh"; String[] command = { bash, script }; System.out.println("Starting execute the script"); ProcessBuilder processBuilder = new ProcessBuilder(command); Map<String, String> env = processBuilder.environment(); env.put("ENV_KEY", "ENV_VALUE"); Process process =
🌐
W3Docs
w3docs.com › java
How to run Unix shell script from Java code?
To run a Unix shell script from Java code, you can use the Runtime.getRuntime().exec() method to execute the script.
🌐
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
🌐
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...
🌐
Mkyong
mkyong.com › home › java › java – run shell script on a remote server
Java - Run shell script on a remote server - Mkyong.com
October 1, 2020 - 1.2 In local, we can use the below code to run or execute the above shell script in a remote server. ... package com.mkyong.io.howto; import com.jcraft.jsch.*; import java.io.IOException; import java.io.InputStream; public class RunRemoteScript { private static final String REMOTE_HOST = "1.1.1.1"; private static final String USERNAME = ""; private static final String PASSWORD = ""; private static final int REMOTE_PORT = 22; private static final int SESSION_TIMEOUT = 10000; private static final int CHANNEL_TIMEOUT = 5000; public static void main(String[] args) { String remoteShellScript = "/ro
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());