rsync : Recursively sync all files while ignoring the directory structure

后端 未结 4 849
一生所求
一生所求 2021-02-12 18:45

I am trying to create a bash script for syncing music from my desktop to a mobile device. The desktop is the source.

Is there a way to make rsync recursively sync files

4条回答
  •  伪装坚强ぢ
    2021-02-12 19:42

    The answer to your question: No, rsync cannot do this alone. But with some help of other tools, we can get there... After a few tries I came up with this:

    rsync -d --delete $(find . -type d|while read d ; do echo $d/ ; done) /targetDirectory && rmdir /targetDirectory/* 2>&-
    

    The difficulty is this: To enable deletion of files at the target position, you need to:

    1. specify directories as sources for rsync (it doesn't delete if the source is a list of files).
    2. give it the complete list of sources at once (rsync within a loop will give you the contents of the last directory only at the target).
    3. end the directory names with a slash (otherwise it creates the directories at the target directory)

    So the command substitution (the stuff enclosed with the $( )) does this: It finds all directories and adds a slash (/) at the end of the directory names. Now rsync sees a list of source directories, all terminated with a slash and so copies their contents to the target directory. The option -d tells it, not to copy recursively.

    The second trick is the rmdir /targetDirectory/* which removes the empty directories which rsync created (although we didn't ask it to do that).

    I tested that here, and deletion of files removed in the source tree worked just fine.

提交回复
热议问题