Assuming I have the following directories:



... (assume I have 100 more directories/ dir[n])

and I want to create a soft link to the source directory (let's call the new directory 'target') with all of the directories within the source directory but only sub1 and sub3 subdirectories.

What is the correct syntax to do this? e.g.,

cd target
ln -s /source/**/sub1 .
ln -s /source/**/sub3 .

UPDATE to show the expected output:


  • updated original post to show what the expected result would be Commented May 15, 2020 at 21:12

1 Answer 1


Assuming you're using bash, you could use this loop:

cd target
for dir in /source/*/sub{1,3}; do
  parentdir=${dir%/*}        # remove last directory, e.g. `/sub1`
  parentdir=${parentdir##*/} # leave the directory name, e.g. `dir1`
  mkdir -p "$parentdir"
  ln -s "$dir" -t "$parentdir"

Add the -r option to ln if the path to the source directory should be a relative path.

  • I thought there might be a simpler (one or two liner) solution, but I did wind up doing something like this - i.e., a bash script to go through the directories and handle each one. Thank you. Commented May 15, 2020 at 22:27

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .