Dan
Dan

Reputation: 195

Unable to rsync files based on a pattern using java

I have a remote Linux machine which i would like to pull files from using rsync based on a specific pattern in the file on a local machine.

When i am in the terminal window I am able to perform this task using the next command:

rsync -avzrm --include '**/someDir/*MG*' --include '*/' --exclude '*' -e "ssh -i /home/localUser/.ssh/id_rsa -l remoteUser" [email protected]:/home/remoteUser/baseDir/ /home/localUser/testDir/

As a result of this command I am able to copy all the files from within the baseDir directory and its sub directories that contain 'MG' in their name.

I am trying to achieve the same result using a java code:

public class DataDumper {
    public static void main (String[] args){
        try {

            String[] cmd = new String[]{"rsync", "-avzrm", "--include", "'**/someDir/*MG*'", "--include", "'*/'", "--exclude", "'*'", 
                                        "-e", "ssh -i /home/localUser/.ssh/id_rsa -l ec2-user",
                                        "[email protected]:/home/remoteUser/baseDir/", "/home/localUser/testing"};
            Process p = new ProcessBuilder().command(cmd).inheritIO().start();
        } 
        catch (IOException ex) {ex.printStackTrace();}
        catch (Throwable th) {th.printStackTrace();}
    }
}

But, i am ending up pulling all the files inside the baseDir directory. What am i doing wrong? why would java not recognize the include and exclude options? Any help would be appreciated. Thank you.

My problem is not executing the command. My problem is that some of the arguments of the command are ignored from some reason.

Upvotes: 0

Views: 404

Answers (1)

Kenster
Kenster

Reputation: 25439

... "--include", "'**/someDir/*MG*'", "--include", "'*/'", "--exclude", "'*'"

Remove the single quotes from the patterns. They're being passed to rsync literally, and rsync is probably interpreting them as part of the filenames that it should look for.

In short, try this:

... "--include", "**/someDir/*MG*", "--include", "*/", "--exclude", "*"

The reason you use single quotes for for these fields on the command line is to prevent the * characters from being interpreted by the shell that is interpreting your commands. Single-quoting the arguments containing * will cause the shell to remove the single quotes and pass the * characters literally to the rsync program.

When you're running rsync through java's ProcessBuilder there is no shell, so there's no need to protect the * characters. But there's also nothing to remove the single quote characters.

Upvotes: 1

Related Questions