Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not use && operator in Runtime.exec() + linux

I'm trying to run an executable from Java with the code pasted below. By using the && operator in the terminal I can both navigate to and run the executable with a single command. I am trying to pass the same command through the Runtime.getRuntime().exec() command but it doesn't seem to like the && operator. Does anyone know a work around for this? In the code posted below I am just passing "cd && pwd" as a test case; an even simpler command but it still doesn't work. Thanks

try{
                int c;
                textArea.setText("Converting Source Code to XML");
                //String[] commands = {"/bin/bash", "-c", "cd /home/Parallel/HomeMadeXML", "&&", "./src2srcml --position" + selectedFile.getName() + "-o targetFile.xml"};
                String commands = "bash -c cd && pwd";
                System.out.println(commands);
                Process src2XML = Runtime.getRuntime().exec(commands);
                InputStream in1 = src2XML.getErrorStream();
                InputStream in2 = src2XML.getInputStream();
                while ((c = in1.read()) != -1 || (c = in2.read()) != -1) {
                        System.out.print((char)c);
                    }
                src2XML.waitFor();
                }
            catch(Exception exc){/*src2srcml Fail*/}
            }
like image 244
Nick Avatar asked Jun 22 '26 23:06

Nick


1 Answers

You want to run a command, you have to use exactly three arguments: bash the executable, -c the flag to execute a command, and a third shell command.

You are trying to pass 5, where the last three are individual fragments of one command.

Here's an example. Note how the shell command is only one argument:

String[] commands = { "/bin/bash", "-c", "cd /tmp && touch foobar" };
Runtime.getRuntime.exec(commands);

When executed, you'll find a file foobar created in your /tmp.

like image 127
that other guy Avatar answered Jun 24 '26 13:06

that other guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!