Rsync 命令在 java 中不起作用

Rsync command not working in java

以下命令直接起作用:

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

但是当 运行 通过 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;
    }

我收到错误:

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]

解决方案答案如下:

ProcessBuilder对象需要初始化如下:

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

shell 在将参数传递给命令之前处理引号。

您的命令行的这一部分开始发挥作用:

 'protect .git/**/*'

shell 将此解释为单个参数:

 protect .git/**/*

如果一开始没有单引号,shell 会是:

  • 将其解释为两个参数(因为space)
  • 扩展的 glob 字符,如“*”

解决办法是通过:

"protect .git/**/"

作为您的 Java 参数之一,而不是 "'protect .git/**/*'"

您可能遇到与 ~ 类似的问题,shell 将扩展到您的主目录。