8

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/{} \;

4 Answers 4

14

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
2

Perhaps I am missing something, other then this needs to be run each time a new directory is created under base. This works for me.

ln -s /base/* /target && ls -l /target
1
  • 1
    This will symlink everything thought, if you need to exclude, it might get more complicated. Dec 2, 2015 at 23:02
1

I'd try:

find /home/chris/folder1 -type d -maxdepth 1 -mindepth 1 -print0 | xargs -0 ln -s -t /home/john/folder2

I'm not a fan of the -exec argument to find, and not a fan of figuring out exactly how to escape literals, so I generally swing to find + xargs.

0

Having stumbled upon the answer which looks similar to what questioner is looking for, I'd thought I'd add an update for future people looking at this.

So the key is to make sure that the target directory does not already exist!

Example:

  1. Delete the target directory: target-directory
  2. Run: ln -s /path/to/base-directory/ /path/to/target-directory

So, for the original question:

  1. Delete the directory: folder2
  2. Run: ln -s /home/chris/folder1/ /home/john/folder2

I hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy