symlink-copying a directory hierarchy

核能气质少年 提交于 2019-11-28 19:21:56

I googled around a little bit and found a command called lns, available from here.

I just did a quick test on a linux box and cp -sR /orig /dest does exactly what you described: creates a directory hierarchy with symlinks for non-directories back to the original.

cp -as /root/absolute/path/name dest_dir

will do what you want. Note that the source name must be an absolute path, it cannot be relative. Else, you'll get this error: "xyz-file: can make relative symbolic links only in current directory."

Also, be careful as to what you're copying: if dest_dir already exists, you'll have to do something like:

cp -as /root/absolute/path/name/* dest_dir/
cp -as /root/absolute/path/name/.* dest_dir/

Starting from above the original & new directories, I think this pair of find(1) commands will do what you need:

find original -type d -exec mkdir new/{} \;
find original -type f -exec ln -s {} new/{} \;

The first instance sets up the directory structure by finding only directories in the original tree and recreating them in the new tree. The second creates the symlinks to the original files in the new tree.

There's also the "lndir" utility (from X) which does such a thing; I found it mentioned here: Debian Bug report #301030: can we move lndir to coreutils or debianutils? , and I'm now happily using it.

If you feel like getting your hands dirty Here is a trick that will automatically create the destination folder, subfolders and symlink all files recursively.

In the folder where the files you want to symlink and sub folders are:

  1. create a file shell.sh:

    nano shell.sh

  2. copy and paste this charmer:

#!/bin/bash

export DESTINATION=/your/destination/folder/
export TARGET=/your/target/folder/

find . -type d -print0 | xargs -0 bash -c 'for DIR in "$@"; 
do
  echo "${DESTINATION}${DIR}"
  mkdir -p "${DESTINATION}${DIR}"        
  done' -


find . -type f -print0 |  xargs -0 bash -c 'for file in "$@"; 
do
  ln -s  "${TARGET}${file}"  "${DESTINATION}${file}"
   done' -
  1. save the file ctrl+O
  2. close the file ctrl+X
  3. Make your script executable chmod 777 shell.sh

  4. Run your script ./shell.sh

Happy hacking!

I know the question was regarding shell, but since you can call perl from shell, I wrote a tool to do something very similar to this, and posted it on perlmonks a few years ago. In my case, I generally wanted directories to remain links until I decide otherwise. It'd be a fairly trivial change to do this automatically and recursively.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!