Bash – Symlink all subdirectories in a directory to another directory

bashdirectoryfindsymlink

I'm trying to symlink every directory in a folder to another folder. For example, in the structure below, I need the subfolders symlinked to folder2.

- /home/chris/folder1
-- subfolder1
-- subfolder2

- /home/john/folder2
-- subfolder1
-- subfolder2

This is what I have tried so far, but my bash skills are rusty and this does not work.

find /home/chris/folder1 -type d -maxdepth 1 -mindepth 1 -exec ln -s {} /home/john/folder2/{} \;

Best Answer

Assuming this layout:

% tree -L 2
.
├── top-1
└── top-2
    ├── sub-1
    ├── sub-2
    └── sub-3

And this desired output:

% tree -L 2
.
├── top-1
│   ├── sub-1 -> /tmp/sf-582772/top-2/sub-1
│   ├── sub-2 -> /tmp/sf-582772/top-2/sub-2
│   └── sub-3 -> /tmp/sf-582772/top-2/sub-3
└── top-2
    ├── sub-1
    ├── sub-2
    └── sub-3

And this version of find:

% find --version
find (GNU findutils) 4.4.2

Use:

find /tmp/sf-582772/top-2/ -maxdepth 1 -mindepth 1 -type d -exec ln -s '{}' /tmp/sf-582772/top-1/ \;

Replacing the full paths given here with the directories you need. Here is a version with relative paths:

% pwd
/tmp/sf-582772
% find top-2 -maxdepth 1 -mindepth 1 -type d -exec ln -s ../'{}' top-1/ \;

Gives:

% tree -L 2
.
├── top-1
│   ├── sub-1 -> ../top-2/sub-1
│   ├── sub-2 -> ../top-2/sub-2
│   └── sub-3 -> ../top-2/sub-3
└── top-2
    ├── sub-1
    ├── sub-2
    └── sub-3
Related Question