symlink-copying a directory hierarchy

前端 未结 7 1632
孤独总比滥情好
孤独总比滥情好 2020-12-13 19:38

What\'s the simplest way on Linux to \"copy\" a directory hierarchy so that a new hierarchy of directories are created while all \"files\" are just symlinks pointing back to

相关标签:
7条回答
  • 2020-12-13 19:55

    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.

    0 讨论(0)
  • 2020-12-13 20:00

    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!

    0 讨论(0)
  • 2020-12-13 20:01

    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.

    0 讨论(0)
  • 2020-12-13 20:02

    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.

    0 讨论(0)
  • 2020-12-13 20:03
    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/
    
    0 讨论(0)
  • 2020-12-13 20:09

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

    0 讨论(0)
提交回复
热议问题