0

I'm having a challenge with sudo invoked commands using both ProcessBuilder and Runtime.exec. I am thinking that ProcessBuilder is overall the better solution but both produce the same result - they execute shell commands fine on Ubuntu, but if I try to do a sudo -i mysql command for example:

    public static void runProcess(String[] process) {
        String s = null;
        try { 
            Process p = new ProcessBuilder(process).start();
            BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
            BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
            while ((s = stdInput.readLine()) != null) { System.out.println(s); }
            while ((s = stdError.readLine()) != null) { System.out.println(s); }
        } catch (IOException e) { e.printStackTrace(); }
    }   

These 2 commands work:

        String[] cmdArgs0 = { "sudo", "echo", "Done" };
        runProcess(cmdArgs0);

        String[] cmdArgs1 = { "bash", usbDrivePath+"/ASWebUI/Install.sh" };
        runProcess(cmdArgs1);

But this does not:

        String[] cmdArgs2 = { "sudo", "-i", "mysqldump", "Core", ">", cachePath+"/SQLDumps/Core.sql" };
        runProcess(cmdArgs2);

Error:

mesg: ttyname failed: Inappropriate ioctl for device
mysqldump: Couldn't find table: ">"

1 Answer 1

1

ProcessBuilder doesn't allow you to redirect the output using > character. Instead you can use processBuilder.redirectOutput() method to specify the desired output.

File dumpFile = new File("Core.sql");
processBuilder.redirectOutput(Redirect.to(dumpFile));

Or even use --result-file option of mysqldump to specify the dump file:

mysqldump [options] --result-file=dump.sql
Sign up to request clarification or add additional context in comments.

1 Comment

@user3260912 Glad to help! Please check my last edit to the answer, I've changed Redirect.appendTo(dumpFile) to Redirect.to(dumpFile) since first one corresponds to >> instead of >.

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.