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());
🌐
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); } } }
🌐
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"); } } ProcessBuilder is used to create operating system processes.
🌐
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 - suppose you want to execute a shell script with attributes like admin,password,url like show in below : ... String cmd= " /home/jay/sam_script.sh admin passwod 127.0.0.1" ; ProcessBuilder pb = new ProcessBuilder(cmd.split(" ")); Process pr = pb.start();
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - 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 ...
🌐
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
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 › 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 ...
🌐
Adobe Experience League
experienceleaguecommunities.adobe.com › home › product communities › adobe experience manager › adobe experience manager sites › how to execute a shell script using processbuilder from sling servlet
How to execute a shell script using ProcessBuilder from Sling Servlet | Community
October 21, 2016 - If you observe closely PWD=/mnt/crx/author is the path where AEM internal process is looking at, USR=crx is the User that AEM is using internally to run the code. So i copied my "shell script" to "/mnt/crx/author" and also gave execute permission to user "crx".
🌐
Wordpress
singztechmusings.wordpress.com › 2011 › 06 › 21 › getting-started-with-javas-processbuilder-a-sample-utility-class-to-interact-with-linux-from-java-program
Getting started with Java’s ProcessBuilder: A simple utility class to interact with Linux from Java program |
June 23, 2011 - i need to pass arguments to the shell script as below · params = java.util.Arrays.asList(“./app/bin/testRunner.sh” “-n1” “-lTestScript” “-f./reports/snbc/”); ProcessBuilder processBuilder = new ProcessBuilder(params);
Find elsewhere
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.

🌐
To The New
tothenew.com › home › executing linux shell command using processbuilder
Executing linux shell command using ProcessBuilder | TO THE NEW Blog
December 19, 2016 - [java]ProcessBuilder pb = new ProcessBuilder("convert", "-adaptive-resize", "${width}x${height}!", sourceFilePath, destinationFilePath); Process p = pb.start() p.waitFor() [/java] It works seemlessly!!!
🌐
Stack Overflow
stackoverflow.com › questions › 50506402 › cant-run-shell-script-with-processbuilder
java - Can't run shell script with ProcessBuilder - Stack Overflow
I adopted the code from one of the similar questions: Process p = null; ProcessBuilder pb = new ProcessBuilder("scr.sh"); pb.directory(new File("/Users/alex/")); p = pb.start();
🌐
Softorks
softorks.com › en › java › how-to-execute-shell-command-java-macos-processBuilder.php
Java - Execute Shell Command Using ProcessBuilder - MacOs
August 20, 2019 - import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; public class ExecuteShellComandProcessBuilder { public static void main (String [] args) throws IOException, InterruptedException{ String [] command = {"ping", "google.com"}; ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(System.getProperty("user.home"))); try { Process process = processBuilder.start(); BufferedReader reader = new BufferedReader (new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } int exitCode = process.waitFor(); System.out.println ("\nExited with error code : " + exitCode); } catch (IOException e) { e.printStackTrace(); } } }
🌐
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.
🌐
Mkyong
mkyong.com › home › java › java processbuilder examples
Java ProcessBuilder examples - Mkyong.com
January 19, 2019 - 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 ...
🌐
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).
🌐
Stack Overflow
stackoverflow.com › questions › 38137881 › how-to-run-sh-file-using-process-builder
java - How to run .sh file, using process builder? - Stack Overflow
April 26, 2017 - Process pb = new ProcessBuilder("/bin/bash","/my/file.sh").start(); I already looking for the answer, but I still failed to run the .sh file, even I do the same thing with people that already done it.
Top answer
1 of 2
4

When you start a process (pb.start()) you get back a Process instance. If your script reads input or writes output to stdout or stderr you need to handle this on separate threads using Process.getInputStream(), ...getOutputStream() and getErrorStream(). If you don't do this the process can hang. You also should call Process.waitFor() and then Process.exitValue() to get the return status of the process. If it's a negative number then the system was unable to launch your script.

EDIT: Here is a short simplified example. This is a toy only and will work reliably ONLY under the following conditions:

  1. The script does not require any input

  2. The script does not produce a large amount of output on both stdout and stderr. If it does, then since the program reads all of stdout before stderr, the stderr buffer may fill up and block the process from completing. In a 'real' implementation you would read stdout and stderr in separate threads (hint, wrap the loadStream() method in a class that implements Runnable).

 

public class PBTest
{
    public static void main(String[] args) throws Exception
    {
        ProcessBuilder pb = new ProcessBuilder("sc","query","wuauserv");
        Process p = pb.start();
        String output = loadStream(p.getInputStream());
        String error  = loadStream(p.getErrorStream());
        int rc = p.waitFor();
        System.out.println("Process ended with rc=" + rc);
        System.out.println("\nStandard Output:\n");
        System.out.println(output);
        System.out.println("\nStandard Error:\n");
        System.out.println(error);
    }

    private static String loadStream(InputStream s) throws Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(s));
        StringBuilder sb = new StringBuilder();
        String line;
        while((line=br.readLine()) != null)
            sb.append(line).append("\n");
        return sb.toString();
    }
}
2 of 2
2

The problem was not on the way I called the script, which was right.
But it was inside the script. At first it was:

#!/bin/bash
inputFolder=$1
outputFolder=$2 

cd $inputFolder

for file in `ls ` ; do
ffmpeg -i $inputFolder/$file -ar 22050 $outputFolder/$file.mp4 
done

But I got ffmpeg command not found, so I changed it to:

#!/bin/bash
inputFolder=$1
outputFolder=$2 

cd $inputFolder

for file in `ls ` ; do
/usr/local/bin/ffmpeg -i $inputFolder/$file -ar 22050 $outputFolder/$file.mp4 
done  

with the hole path. But I have still doubts, why this is necessary, if I have ffmpeg in my path and I cand execute in console direclty form any directory?? If someone can give me an answer, it will be welcome :)