Search code examples
rsync

rsync: how to copy several subdirectories in just one calling


How to join this rules:

rsync -av --delete --progress ./directory/subdirectory1 /remote
rsync -av --delete --progress ./directory/subdirectory2 /remote

to just one line.

This does not work:

rsync -av --delete --progress ./directory/subdirectory1 ./directory/subdirectory2 /remote

because it copies the files in subdirectories subdirectory1 and subdirectory2 and not the subdirectories itselves.

The desired output would be:

ls /remote/
subdirectory1
subdirectory2

copying subdirectories as a whole.


Solution

  • You can include the --relative (-R) flag to specify that source paths should be remembered in the destination. The optional /./ part in the source path marks the point from which the path should be remembered.

    rsync -avR --delete --progress directory/./subdirectory1 directory/./subdirectory2 /remote
    

    Worked example

    # Set up the scenario
    mkdir /tmp/62569606
    cd /tmp/62569606
    
    mkdir -p src/sub1 src/sub2 dst
    touch src/sub1/file1 src/sub2/file{1,2}
    
    ls -R src
    
    # Run the rsync command
    rsync -av src/./sub1 src/./sub2 dst/
    

    Here's the output

    sending incremental file list
    sub1/
    sub1/file1
    sub2/
    sub2/file1
    sub2/file2
    
    sent 272 bytes  received 81 bytes  706.00 bytes/sec
    total size is 0  speedup is 0.00
    

    And the evidence (ls -R dst)

    dst:
    sub1  sub2
    
    dst/sub1:
    file1
    
    dst/sub2:
    file1  file2