我想cp
在终端中复制一个符号相对的链接到另一个目录,并且我希望副本保持相对指向原始目标文件。
我怎样才能简单地做到这一点?
最小示例:
考虑文件fileAX
和相对的软链接mylink
somepath/folderA/folderX/fileAX
somepath/folderB/folderY/mylink -> ../../folderA/folderX/fileAX
现在我想复制一份mylink
并folderB
指向原始文件fileAX
。它看起来应该像这样:
somepath/folderB/mylinkcopy -> ../folderA/folderX/fileAX
该怎么办呢?
答案1
两者都没有转换符号链接目标的选项cp
(功能更强大的也没有rsync
)。您必须自己进行转换:
% realpath --relative-to=. "$(readlink --canonicalize-missing folderY/mylink)"
../folderA/folderX/fileAX
% ln -s "$(realpath --relative-to=. "$(readlink --canonicalize-missing "folderY/mylink")")" mylinkcopy
% ls -lR
.:
total 4
drwxr-xr-x 2 muru muru 4096 May 22 22:01 folderY
lrwxrwxrwx 1 muru muru 25 May 22 22:17 mylinkcopy -> ../folderA/folderX/fileAX
./folderY:
total 0
lrwxrwxrwx 1 muru muru 28 May 22 22:00 mylink -> ../../folderA/folderX/fileAX
或者,对于这种特定情况,您可以使用tar
's--transform
来s:[^/]*/::
删除第一个路径组件。我没想到它也能转换符号链接目标路径,但它确实做到了:
% tar c -C folderY mylink | tar xv --transform 's:[^/]*/::'
mylink
% ls -lR
.:
total 4
drwxr-xr-x 2 muru muru 4096 May 22 22:01 folderY
lrwxrwxrwx 1 muru muru 25 May 22 22:00 mylink -> ../folderA/folderX/fileAX
lrwxrwxrwx 1 muru muru 25 May 22 22:17 mylinkcopy -> ../folderA/folderX/fileAX
./folderY:
total 0
lrwxrwxrwx 1 muru muru 28 May 22 22:00 mylink -> ../../folderA/folderX/fileAX