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
🌐
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.
🌐
Redpill Linpro
redpill-linpro.com › techblog › 2024 › 02 › 21 › java-21-shell-scripts.html
Portable Java shell scripts with Java 21 – /techblog
February 21, 2024 - Finally, when the Java process has terminated, the exit code from the Java process ($?) is propagated as the exit code of the script so that users of the script can handle errors in a predictable way. It also prevents the program loader from attempting to execute the rest of the file: ///usr/bin/env java --source 21 --enable-preview "$0" "$@"; exit $? As long as you have Java 11 or higher, you can still make Java shell scripts, you just need to declare a class and make the main method static:
🌐
Oracle
docs.oracle.com › cd › E14507_01 › apirefs.1112 › e14133 › java002.htm
Shell Script Example
#!/bin/sh CLASSPATH=.:$ORACLE_HOME/search/lib/search_adminapi_wsclient.jar:$ORACLE_BASE/jrockit_160_14_R27.6.5-32/jre/lib/rt.jar # Compile $ORACLE_BASE/jrockit_160_14_R27.6.5-32/bin/javac -cp $CLASSPATH CreateWebSource.java # Run $ORACLE_BASE/jrockit_160_14_R27.6.5-32/jre/bin/java -cp $CLASSPATH CreateWebSource $@ To run the script, include these arguments on the command line: webServiceURL: The Web Service URL for the Administration API in the following format. Replace host:port with the appropriate values. ... sh compileAndRun.sh http://host:7777/search/api/admin/AdminService eqsys password http://example.com/index.htm
🌐
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.
🌐
Medium
medium.com › @benweidig › java-for-shell-scripting-5b5af5860c47
Java for shell scripting. How to use Java self-contained shell… | by Ben Weidig | Medium
September 16, 2023 - Java for shell scripting No matter what your daily driver is, most of us also have to write some shell scripts to automate stuff. Usually, we would use bash script, Python, Perl ,or some other …
🌐
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).
🌐
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.
Find elsewhere
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();
        }
🌐
Belief Driven Design
belief-driven-design.com › java-for-shell-scripting-cafd6de3fa2
Java for Shell Scripting | belief driven design
And you can put the Jar in the shell script itself: ... # Create a new file 'myjavacli' with a shebang echo "#\!/usr/bin/java -jar" > myjavacli # Adding the Jar content cat my-java-app.jar >> myjavacli # Make it executable chmod +x myjavacli # Now you can run it!
🌐
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…
🌐
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.
🌐
Alvin Alexander
alvinalexander.com › blog › post › java › unix-shell-script-i-use-for-compiling-java-programs
A Linux shell script to compile Java source code files that require building a CLASSPATH | alvinalexander.com
April 28, 2019 - Note that you will want to change the value of the variable PROGRAM_NAME to the name of your Java class file that contains the main method for your app.
🌐
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 the above example, we’re searching for all the java files inside the src directory and piping the results into another process to count them. To learn about other improvements made to the Process API in Java 9, check out our great article on Java 9 Process API Improvements. As we’ve seen in this quick tutorial, we can execute a shell command in Java in two distinct ways.
🌐
W3Docs
w3docs.com › java
How to run Unix shell script from Java code?
Here is an example of how to do this: String scriptPath = "/path/to/script.sh"; Process process = Runtime.getRuntime().exec(scriptPath); process.waitFor(); int exitValue = process.exitValue(); if (exitValue == 0) { System.out.println("Script ...
🌐
Medium
schlining.medium.com › java-for-shell-scripting-dc81ac3c2dd1
Java for Shell Scripting. Yes, you read the title right. | by Brian Schlining | Medium
December 29, 2023 - Below is an alternative, using /// instead of #!. I tested this in a variety of shells on a Mac and it worked fine, but be warned that using /// may not work on all systems. ///usr/bin/env -S java --source 21 --enable-preview "$0" "$@" ; exit $? void main(String[] args) { var name = args.length > 0 ? args[0] : "World"; System.out.println(STR."Hello, \{name}"); } Now my code editor is happy and I can pass arguments to my program: ... While this approach is suitable for simple scripts, for those requiring external dependencies, consider exploring:
🌐
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 ...
🌐
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
🌐
GitHub
gist.github.com › sangupta › 9d432f8368811533f99fec44b3ea9428
A simple shell script to run a Java program from Linux shell in the background · GitHub
This is a simple script to run a Java program from Linux shell in the background - so that the process does not terminates when you log out of the shell.