Search code examples
javacmdruntimersyncprocessbuilder

Rsync using java Runtime.getRuntime().exec() with double qoute in command


Hello I am trying to execute following :

Process p = null;
StringBuffer rbCmd = new StringBuffer();

rbCmd.append("rsync -e \"ssh -i /root/.ssh/key\" -va --relative /home/lego/hyb/abc/PVR2/Testdata/./R887/SCM/System root@myMachine:/xyz/data/SCMdata/");

p = Runtime.getRuntime().exec(rbCmd.toString());

But I am getting following error on command line.Command executes correctly on command line

Missing trailing-" in remote-shell command. rsync error: syntax or usage error (code 1) at main.c(361) [sender=3.0.6]

Issue is because of double quotes inside the command where I mention ssh key.

Please help with correction.


Solution

  • Your approach won't work because Runtime.exec() does not realize that "ssh -i /root/.ssh/key" is a single argument to rsync. Escaping the double-quotes keeps the compiler happy, but doesn't remove the fundamental problem, which is the limits of the built-in tokenizer.

    You might have more luck with something like this:

    Process p = Runtime.getRuntime().exec
        (new String[]{"rsync", "-e", "ssh -i /root/.ssh/key", "-va" "--relative" ... });
    

    That is, tokenize the command line yourself, and form the individual tokens into a String[]. You're deciding in advance what the arguments to rsync are, rather than allowing exec() to figure it out (wrongly).

    Don't forget that if rsync produces any output, you'll need to arrange for your application to consume its stdout and stderr, or it could stall.