Try replacing

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};

with

String[] command = {"/teste/teste_back/script.sh", argument1, argument};

Refer ProcessBuilder for more information.

ProcessBuilder(String... command)

Constructs a process builder with the specified operating system program and arguments.

Answer from Jagan N on Stack Overflow
Top answer
1 of 3
6

Try replacing

String[] command = {"/teste/teste_back/script.sh, "+argument1+", "+argument+""};

with

String[] command = {"/teste/teste_back/script.sh", argument1, argument};

Refer ProcessBuilder for more information.

ProcessBuilder(String... command)

Constructs a process builder with the specified operating system program and arguments.

2 of 3
5

You can define a method with ProcessBuilder.

public static Map execCommand(String... str) {
    Map<Integer, String> map = new HashMap<>();
    ProcessBuilder pb = new ProcessBuilder(str);
    pb.redirectErrorStream(true);
    Process process = null;
    try {
        process = pb.start();
    } catch (IOException e) {
        e.printStackTrace();
    }

    BufferedReader reader = null;
    if (process != null) {
        reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    }

    String line;
    StringBuilder stringBuilder = new StringBuilder();
    try {
        if (reader != null) {
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        if (process != null) {
            process.waitFor();
        }
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

    if (process != null) {
        map.put(0, String.valueOf(process.exitValue()));
    }

    try {
        map.put(1, stringBuilder.toString());
    } catch (StringIndexOutOfBoundsException e) {
        if (stringBuilder.toString().length() == 0) {
            return map;
        }
    }
    return map;
}

You can call the function to execute shell command or script

String cmds = "ifconfig";
String[] callCmd = {"/bin/bash", "-c", cmds};
System.out.println("exit code:\n" + execCommand(callCmd).get(0).toString());
System.out.println();
System.out.println("command result:\n" + execCommand(callCmd).get(1).toString());
🌐
Javasavvy
javasavvy.com › home › running a shell script using process builder in java
Running shell script using process builder java,shell script execution in java
April 20, 2024 - i.e I have to copy a file inside a Unix server the user should give the existing Shell Script name and the Arguments for the SH file is Filename1(Source) and FileName2(Destination) from the FrontEnd UI. cmd.splt(” “) inside the ProcessBuilder worked fine.
🌐
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 processBuilder = new ProcessBuilder(command); Map<String, String> env = processBuilder.environment(); env.put("ENV_KEY", "ENV_VALUE"); Process process = processBuilder.start(); // output the process BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } // wait for the end of process process.waitFor(); System.out.println("Script executed successfully"); } catch (Exception e) { throw new RuntimeException("Can not execute the install script successfully"); } }
🌐
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 to run the same command as above using ProcessBuilder, which is a much clearer way to do that, you can create a list with the command and the required arguments and then pass it to ProcessBuilder instance as command. import java.io.BufferedReader; import java.io.IOException; import ...
🌐
Revisit Class
revisitclass.com › home › execute the shell commands using processbuilder in java
Execute the shell commands using ProcessBuilder in Java -
December 17, 2021 - import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class RunCmdPrompt{ public static void main(String[] args) throws IOException, InterruptedException { String cmd = "dir"; ProcessBuilder builder = new ProcessBuilder(); builder.command("cmd.exe","/c",cmd); Process result = builder.start(); int exitcode=result.waitFor(); System.out.println("Exit code: " + exitcode); if (exitcode == 0) { System.out.println("Success!"); } else { System.out.println("Abnormal failure"); System.out.println("Quitting the program"); System.exit(1); } BufferedReader stdInput = new BufferedReader(new InputStreamReader(result.getInputStream())); String output; while ((output = stdInput.readLine()) != null) { System.out.println(output); } } }
🌐
Unix.com
unix.com › shell programming and scripting
How to run the Shell Script from external directory using java? - Shell Programming and Scripting - Unix Linux Community
October 19, 2017 - Hi, I have created a Shell Script and invoke through java using Process Builder It’s working fine, if (Shell script file ) in the same directory as java file. By Problem: How to run the Shell Script file( resi…
Find elsewhere
🌐
Baeldung
baeldung.com › home › 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.
🌐
Coderanch
coderanch.com › t › 459571 › os › ProcessBuilder-executing-shell-script-java
how to use ProcessBuilder for executing a shell script from java? (GNU/Linux forum at Coderanch)
All exceptions are handles in the shell script and it exits properly from shell script. Regards, Acharya ... You can not use redirections with ProcessBuilder, afaik: Instead you have to open System.err and generate ShellscriptError.err yourself. Together with runtime.exec here is a good explanation: http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html Maybe most of the traps are still traps, even when using ProcessBuilder, which is newer than Runtime.exec.
🌐
OpenJDK
openjdk.org › jeps › 8263697
JEP draft: Safer Process Launch by ProcessBuilder and Runtime.exec
We are changing the default for ProcessBuilder and Runtime.exec to require quoted arguments to have properly balanced quotes and to guard against splitting or merging of arguments. For scripts such as .cmd and .bat, executed by shell programs, the encoding of special characters such as < > & | is modified to prevent implicit access to shell features such as redirection and pipelines.
🌐
CopyProgramming
copyprogramming.com › howto › cannot-launch-shell-script-with-arguments-using-java-processbuilder
Java: Launching shell script with arguments using Java ProcessBuilder is not possible
April 15, 2023 - Solution 2: To pass a Java variable as a parameter to a Unix shell script, you can use the code below: String var1 = "Hi"; ProcessBuilder pb = new ProcessBuilder("/home/gcharpe/bin/java/t1.sh", var1); Solution 1: You mentioned Quartz, so let's explore option #4, which, in my opinion, is the ...
Top answer
1 of 1
8

"(actually it's "ls" but it should work exactly the same way)"

No, it is not. Because the 'ls' process returns immediately after its call. Your omixplayer at the other hand is interactive and will accept commands at runtime.

What you have to do:

  • create a class which implements Runnable and let this class read from the prs.getInputStream(). You will need this because the .read() will block and wait for new data to read.

  • get the OutputStream of the Process object (prs.getOutputStream()). Everything you write to the OutputStream will be read from your omixplayer. Don't forget to flush the OutputStream and every command needs an "\n" at the end to be executed.

Like that:

public class TestMain {
    public static void main(String a[]) throws InterruptedException {

        List<String> commands = new ArrayList<String>();
        commands.add("telnet");
        commands.add("www.google.com");
        commands.add("80");
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.redirectErrorStream(true);
        try {

            Process prs = pb.start();
            Thread inThread = new Thread(new In(prs.getInputStream()));
            inThread.start();
            Thread.sleep(2000);
            OutputStream writeTo = prs.getOutputStream();
            writeTo.write("oops\n".getBytes());
            writeTo.flush();
            writeTo.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class In implements Runnable {
    private InputStream is;

    public In(InputStream is) {
        this.is = is;
    }

    @Override
    public void run() {
        byte[] b = new byte[1024];
        int size = 0;
        try {
            while ((size = is.read(b)) != -1) {
                System.err.println(new String(b));
            }
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

P.S.: Keep in mind this example is quick an dirty.

🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - In Java, we can use ProcessBuilder or Runtime.getRuntime().exec to execute external shell command : ProcessBuilder processBuilder = new ProcessBuilder(); // -- Linux -- // Run a shell command processBuilder.command("bash", "-c", "ls /home/mkyong/"); // Run a shell script //processBuilder.command("path/to/hello.sh"); // -- Windows -- // Run a command //processBuilder.command("cmd.exe", "/c", "dir C:\\Users\\mkyong"); // Run a bat file //processBuilder.command("C:\\Users\\mkyong\\hello.bat"); try { Process process = processBuilder.start(); StringBuilder output = new StringBuilder(); BufferedRead
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - Taking a look at how the ProcessBuilder ... a String[] cmdarray, and that's enough to get it running. Alternatively, we can supply it with optional arguments such as the String[] envp and File dir....
🌐
Stack Overflow
stackoverflow.com › questions › 33360737 › running-a-shell-script-using-process-builder-in-java
Running a shell script using process builder in java - Stack Overflow
But I am not sure how it works in java. so to make this work, I made another script called command.sh which just has this shell commmand - cat input.txt | shellscript.sh · and i placed them all in the same directories. When i run it, there are no errors but the commands inside the script does not seem to run. public class testing { public static void main(String[] args) throws IOException,InterruptedException { Process p = new ProcessBuilder("/bin/sh", "/Random Files/command.sh").start(); } }
🌐
Coderanch
coderanch.com › t › 709883 › java › Add-parameters-ProcessBuilder
Add parameters to ProcessBuilder (Java in General forum at Coderanch)
May 17, 2019 - Add paramters to the ProcessBuilder. The username and the pw is always the same, thats the reason why do this automatically.