linux copy symlinks and their hierarchy

Say I have the following structure:

root
|
\
  dir1
  |
  | \
  |  libfoo.so.4.2
  |  libfoo.so.4 -> libfoo.so.4.2
  |  libfoo.so -> libfoo.so.4
     JunkThatShouldntBeCopied
  dir2

I would like to copy libfoo.so and using it also libfoo.so.4 and libfoo.so.4.2 into root/dir2.

  • I can't copy the entire directory that contains them since it contains a lot of other files I do not want.
  • I also don't know the exact names of the files that libfoo.so points to.

How can I do that?


I can think of something like this:

trace() {
  arr+=("$1")
  local next="$(readlink "$1")"
  if [ -n "$next" ]; then
    trace "$next"
  fi
}
$ cd /tmp/a/
$ unset arr; trace 3
$ rsync -vl "${arr[@]}" /tmp/b/
created directory /tmp/b
1
2 -> 1
3 -> 2

sent 125 bytes  received 70 bytes  390.00 bytes/sec
total size is 2  speedup is 0.01
$ 

cp -Pp /root/dir1/libfoo.so* /root/dir2/