#Run command in terminal in java

10 messages · Page 1 of 1 (latest)

blazing plover
#

I am trying to run a command in the terminal in java. This is the code I wrote so far:

public class Terminal {
    public static void runCommand(String command) {
        LogManager.log("Recieved command: " + command);
        try {
            ProcessBuilder builder = new ProcessBuilder();
            String[] args = command.split(" ");
            builder.command(args);
            builder.directory(FileManager.getDir());
            Process process = builder.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            //Runtime.getRuntime().exec(command);
        } catch (IOException e) { LogManager.error(e.toString()); }
    }
}

I am reading documentation and tutorials for ProcessBuilder and I am not sure what I am doing wrong since nothing happens when I run this. This is ran when the program starts:

Terminal.runCommand("/bin/bash -c 'echo Test'");

It should work, the command works in the terminal fine but it does not.

coral lakeBOT
#

This post has been reserved for your question.

Hey @blazing plover! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

blazing plover
#

This does get printed: Recieved command: /bin/bash -c 'echo Test'

#

But that's it

rigid flame
#

I think the problem is that it is treating 'echo and Test' as separate arguments

#

whereas it should be echo Test - a single argument without the quotes

#

but you could try Terminal.runCommand("echo Test");

blazing plover
#

that was the issue

#

echo Test needs to be a single argument for /bin/bash I didn't think about it that way tysm