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());
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.

🌐
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 - String cmd = "/home/javasavvy/sample_script.sh"; //String cmd = "D://script.bat" //for windows ProcessBuilder pb = new ProcessBuilder(cmd); try { Process process = pb.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); StringBuilder builder ...
🌐
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 - ProcessBuilder builder = new ProcessBuilder(); if (isWindows) { builder.command("cmd.exe", "/c", "dir"); } else { builder.command("sh", "-c", "ls"); } builder.directory(new File(System.getProperty("user.home"))); Process process = builder.start(); ...
🌐
Revisit Class
revisitclass.com › home › execute the shell commands using processbuilder in java
Execute the shell commands using ProcessBuilder in Java -
December 17, 2021 - If you want to run the command prompt commands,you can use the cmd.exe instead of sh in the builder command list.It helps java to identify the environment to run the given commands. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class ...
🌐
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(); } } }
🌐
GitHub
gist.github.com › simonwoo › c21811eddf0392034946
execute a shell script from java.md · GitHub
execute a shell script from java.md ... }; System.out.println("Starting execute the script"); ProcessBuilder processBuilder = new ProcessBuilder(command); Map<String, String> env = processBuilder.environment(); env.put("ENV_KEY", ...
🌐
Mkyong
mkyong.com › home › java › how to execute shell command from java
How to execute shell command from Java - Mkyong.com
January 3, 2019 - Note More Java ProcessBuilder examples · Example to execute shell command host -t a google.com to get all the IP addresses that attached to google.com. Later, we use regular expression to grab all the IP addresses and display it. P.S “host” command is available in *nix system only.
🌐
YouTube
youtube.com › watch
Java - Execute a shell Command Using ProcessBuilder - MacOs - YouTube
Additional Information 1. Class ProcessBuilder: https://docs.oracle.com/javase/8/docs/api/java/lang/ProcessBuilder.html
Published   August 19, 2019
Find elsewhere
🌐
Stack Abuse
stackabuse.com › executing-shell-commands-with-java
Executing Shell Commands with Java
May 18, 2020 - We've used the Runtime and ProcessBuilder classes to do this. Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.
🌐
Adobe Experience League
experienceleaguecommunities.adobe.com › t5 › adobe-experience-manager › how-to-execute-a-shell-script-using-processbuilder-from-sling › m-p › 192942
Solved: How to execute a shell script using ProcessBuilder... - Adobe Experience League Community - 192942
October 23, 2016 - public class ScriptHelper { public static void executeScript(String scriptPath) { log.info("...ScriptHelper.executeScript()"); try { /** Commands for server * "vltexport.sh" - Name of shellscript * "/apps/swa" - Source folder. I'm using these to be copied over' * "/mnt/crx/author/vltdata" - Destination folder */ String[] sendCommand = {"vltexport.sh", "/apps/swa", "/mnt/crx/author/vltdata"}; ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.directory(new File("/mnt/crx/author/vltdata")); log.info("Command options="+Arrays.asList(sendCommand)); processBuilder.command(sendCommand); log.info("Command="+processBuilder.command()); processBuilder.redirectErrorStream(true); //new log.info("Environment:::\n"+processBuilder.environment()); log.info("...
🌐
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
To understand the difference between the two methods have look Difference between ProcessBuilder and Runtime.exec() , also ProcessBuilder vs Runtime.exec() public class ShellCommandsHandler { private static final Logger log = Logger.getLogger(ShellCommandsHandler.class); public static void execute(String script){ try { Process p = Runtime.getRuntime().exec(script); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); String line=null; while((line=input.readLine()) != null) { System.out.println(line); } int exitVal = p.waitFor(); System.out.println("Exited with
🌐
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.
🌐
Mkyong
mkyong.com › home › java › java processbuilder examples
Java ProcessBuilder examples - Mkyong.com
January 19, 2019 - I want to know if there is a way to display the shell script output as it continues to run in the background ( child process ). ... Very useful. You do have the odd mistake. list -> List or string -> String. But helped me a great deal. Cheers ... How i update a file in linux in linux use vi filename-> press key i-> go to the line where modification is required -> update the value -> esc -> :wq how to do these commands in java and how to go to the particular line which needs modification?
🌐
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!!! – @Divya Setia divya@intelligrape.com http://www.intelligrape.com ... String command = “sh -c ls -la $lParam” println(“[$command]”) Process process=command.execute() process.waitFor() println(process.text)
🌐
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
Using the getInputStream() method of Process class output of the executed command can be printed by reading the stream. 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 java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; public class RunningSS { public static void main(String[] args) { Process p; try { List<String> cmdList = n
🌐
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)
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.
🌐
javaspring
javaspring.net › blog › java-execute-shell-command
Java Execute Shell Commands: A Comprehensive Guide — javaspring.net
Here's an example: import ... args) { try { String command = "invalid_command"; ProcessBuilder processBuilder = new ProcessBuilder(command); Process process = processBuilder.start(); // Read the command output ...
🌐
Baeldung
baeldung.com › home › java › core java › guide to java.lang.processbuilder api
Guide to java.lang.ProcessBuilder API | Baeldung
November 26, 2025 - PATH/usr/bin:/bin:/usr/sbin:/sbin SHELL/bin/bash ... Now we’re going to add a new environment variable to our ProcessBuilder object and run a command to output its value: