Cannot run multiple commands in Java terminal

Viewed 59

I cannot run multiple commands using symbols "&&", "&", "||", ";" I checked almost every question that asked this, and I still could not find the answer to my problem. I can successfully run one command in the java command shell but not more than 1. Thank you in advance for your help!

try {

                Process process = Runtime.getRuntime().exec("g++ " + projPath +" -o " + name + " && ./" + name);
                StringBuilder output = new StringBuilder();

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(process.getInputStream()));
                
                BufferedReader errinput = new BufferedReader(
                        new InputStreamReader(process.getErrorStream()));

                String line;
                String err;
                while ((line = reader.readLine()) != null) {
                    output.append(line + "\n");
                }
                while ((err = errinput.readLine()) != null) {
                    output.append(err + "\n");
                }

                int exitVal = process.waitFor();
                if (exitVal == 0) {
                    acc.setExpandedPane(pane1);
                    txt.setStyle("-fx-text-fill: black;");
                    txt.setText(output.toString());
                } else {
                    acc.setExpandedPane(pane1);
                    txt.setStyle("-fx-text-fill: red;");
                    txt.setText(output.toString());
                }

            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
1 Answers

Java does not provide a shell, it just splits the string provided into words and passes it as arguments to the executable mentioned as first word.

Try passing the command to /bin/bash (or another shell of your choosing):

final String innerCommand = "g++ " + projPath +" -o " + name + " && ./" + name;
final String[] command = {"/bin/bash", "-c", innerCommand};
final Process process = Runtime.getRuntime().exec(command);
Related