简体   繁体   中英

Rsync command not working in java

The following commands works directly:

rsync -rtuc --delete-after --exclude '.git*' --filter 'protect .git/**/*' ~/some/source/ ~/some/destination/

But when run via java:

private Boolean syncFiles() {
            // Success flag default to true
            Boolean success = true;
            // Attempt sync repo
            try {
                ProcessBuilder runtimeProcessBuilder = new ProcessBuilder().inheritIO().command(new String[]{
                    "rsync", "-rtuc","--delete-after", "--exclude", "'.git*'", "--filter", "'protect .git/**/*'", "~/some/source/", "~/some/destination/"
                });
                // Wait until process terminates
                int output = runtimeProcessBuilder.start().waitFor();
                // Determine if successful
                if (output == 0) {
                    System.out.println("Backup of " + getSource() + " to " + getDestination()
                            + " was successful");
                } else {
                    System.out.println("Error: rsync returned error code: " + output);
                    success = false;
                }
            } catch (Exception ex) {
                success = false;
                System.out.println("Error:");
                System.out.println(ex.getMessage());
                Logger.getLogger(Rsync.class.getName()).log(Level.SEVERE, null, ex);
            }
            return success;
    }

I get the error:

Unknown filter rule: `'protect .git/**/*'' Error: rsync returned error code: 1 rsync error: syntax or usage error (code 1) at exclude.c(902) [client=3.1.2]

The shell handles quoting before passing the parameters to the command.

The comes into play with this part of your command line:

 'protect .git/**/*'

The shell interprets this as the single parameter:

 protect .git/**/*

If the single quotes had not been there in the first place, the shell would have:

  • interpreted it as two parameters (because of the space)
  • expanded glob characters like "*"

The solution is to pass:

"protect .git/**/"

as one of your Java parameters, rather than "'protect .git/**/*'" .

You may have similar problems with ~ , which the shell will expand to your home directory.

The answer to the solution is as follows:

The ProcessBuilder object needs to be initialised as follows:

ProcessBuilder runtimeProcessBuilder = new ProcessBuilder().inheritIO().command(new String[]{
     "rsync", "-rtuc","--delete-after", "--filter", "protect .git", "--exclude", "'.git*'", "~/some/source/", "~/some/destination/"
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM