2

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 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks, it worked! Sorry, I was having a hard time finding this on web.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.