Rsync: Is it possible to transmit src files as symlinks and copying rest of dir structure

rsyncsymlink

I want to copy the src dir as a template i.e. preserving the same structure. The files in this template dir should point to src directory as symlinks. I am not sure if rsync can do this out of box.

Best Answer

Rsync can only do copies or (sometimes) hard links, not symbolic links. The cp program from GNU coreutils can do what you want, at least if you don't need fancy rsync options such as filtering based on file names. Just use the -s flag, plus -a for recursion.

cp -as source target

If you need filtering, you can use zsh's zmv. The zmv function moves files by default, but you can specify another operation with -S (create symlinks, but this isn't good for your use case because it doesn't copy directories) or -p (specify an arbitrary program, here I use a function that creates any needed directories and then makes a symlink). You can specify a pattern to restrict which files get copied; here I use ^*.dontcopy to omit files with the extension .dontcopy and (m-7) to only process files modified within the last 7 days, plus ^/ to omit directories from the list of files to process.

mkdir_ln () {
  mkdir -p -- $2:t &&
  ln -s -- $1:A $2
}
cd source
zmv -P mkdir_ln -Q '**/^*.dontcopy(m-7^/)' '../target/$f'

Above I use the history modifier (:A) to turn the first argument into an absolute path. If you want to create relative symlinks, you'll have to construct the proper target path, with the right number of ../ components.

mkdir_ln () {
  mkdir -p -- $2:t &&
  ln -s -- ${1//[^/]##/..}/$1 $2
}
Related Question