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
🌐
Kevin Boone
kevinboone.me › exec.html
How to run a shell script from a Java application - Kevin Boone
To invoke the shell to run the script, we might try something like this: ... The -c switch tells the shell to process the next argument as a command. This won't work, either, because ... In my example, I want to invoke something.sh and pass it the argument 42.
🌐
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 - This class implements the Runnable interface, which means any Executor could execute it. Next, we’ll spawn a new process using the .exec() method and use the StreamGobler created previously. For example, we can list all the directories inside the user’s home directory and then print it to the console:
🌐
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 are trying to run shell script on a Windows system! What do you expect ??? Though there are ways to run sh from widows but that will require some work. 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.
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - In this tutorial, we'll cover how to execute shell commands, bat and sh files in Java. We'll be covering examples for all exec() and ProcessBuilder approaches.
🌐
GitHub
gist.github.com › simonwoo › c21811eddf0392034946
execute a shell script from java.md · GitHub
... /** * 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 ...
Find elsewhere
🌐
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. Here is an example of how to do this: String scriptPath = "/path/to/script.sh"; Process process = Runtime.getRuntime().exec...
🌐
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.
🌐
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
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - Example: uptime | sed “s/^.* up \+\(.\+\), \+[0-9] user.*$/\1/” ... Using array parameter is better, because…when some parameter has blank ( ex. “ABC DE” ) it will be treated as 2 parameters…
🌐
Humayun Ahmed Ashik
humayun-ashik.hashnode.dev › execute-shell-script-on-the-remote-server-from-java-project-using-jsch-library
Execute shell script on the remote server from Java project using JSch Library
July 10, 2021 - We need to create a new JSch object first which will execute our shell script file. ... Session session = jsch.getSession(userName, host, port); session.setConfig("StrictHostKeyChecking", "no"); session.setPassword(passWord); session.connect(); ...
🌐
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 = ...
🌐
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.
🌐
Medium
medium.com › se-notes-by-alexey-novakov › shell-script-in-java-8b3339be0280
Shell Script in Java. If you always wanted to write a shell… | by Alexey Novakov | SE Notes by Alexey Novakov | Medium
December 26, 2018 - Apart from the shebang file mode, one can run single-file source-code program via java command directly, for example: java -Dtrace=true --source 11 myprogram some_param1 · Let’s imagine some use case where we could apply this feature: Set Docker image tag for local Docker images and push them to specific Docker registry. Let’s solve it with with shell program in Java.
🌐
Coderanch
coderanch.com › t › 379834 › java › executing-shell-script-java
executing shell script from java (Java in General forum at Coderanch)
October 10, 2016 - Originally posted by Henry Wong: Take a look at the example that I showed you... You still have differences. The version of exec() that I am using is specifying a current working directory. One of the operations prior to executing the command is changing to the current working directory. Henry File file_location = new File("/users/temp/rag"); String file_location1 = "/users/temp/Test.java"; String a_mib_name = "Test269.java"; String cmd[] = new String[] {"/bin/bash", "-c", "ln", "-s", file_location1, a_mib_name}; Runtime rtime = Runtime.getRuntime(); Process child = rtime.exec(cmd, null, file_location); Wrong number of arguments in method.
🌐
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?
Top answer
1 of 2
3

You need Runtime.getRuntime().exec(...). See a very extensive example (don't forget to read the first three pages).

Keep in mind that Runtime.exec is not a shell; if you wish to execute a shell script your command line would look like

/bin/bash scriptname

That is, the shell binary you need is fully qualified (although I suspect that /bin is always in the path). You can not assume that if

myshell> foo.sh

runs,

Runtime.getRuntime.exec("foo.sh");

also runs as you are already in a running shell in the first example, but not in the Runtime.exec.

A tested example (Works on My Linux Machine(TM)), mosly cut-and-past from the previously mentioned article:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ShellScriptExecutor {

    static class StreamGobbler extends Thread {
        InputStream is;

        String type;

        StreamGobbler(InputStream is, String type) {
            this.is = is;
            this.type = type;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line = null;
                while ((line = br.readLine()) != null)
                    System.out.println(type + ">" + line);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    }


    public static void main(String[] args) {
        if (args.length < 1) {
            System.out.println("USAGE: java ShellScriptExecutor script");
            System.exit(1);
        }

        try {
            String osName = System.getProperty("os.name");
            String[] cmd = new String[2];
            cmd[0] = "/bin/sh"; // should exist on all POSIX systems
            cmd[1] = args[0];

            Runtime rt = Runtime.getRuntime();
            System.out.println("Execing " + cmd[0] + " " + cmd[1] );
            Process proc = rt.exec(cmd);
            // any error message?
            StreamGobbler errorGobbler = new StreamGobbler(proc
                    .getErrorStream(), "ERROR");

            // any output?
            StreamGobbler outputGobbler = new StreamGobbler(proc
                    .getInputStream(), "OUTPUT");

            // kick them off
            errorGobbler.start();
            outputGobbler.start();

            // any error???
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}
2 of 2
3

Shell Script test.sh code

#!/bin/sh
echo "good"

Java Code to execute shell script test.sh

      try {
            Runtime rt = Runtime.getRuntime();
            Process pr = rt.exec(new String[]{"/bin/sh", "./test.sh"});

            BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            String line = "";
            while ((line = input.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
        }