用文件替换符号链接

用文件替换符号链接

有没有一种简单的方法可以用它们链接到的文件替换所有符号链接?

答案1

对于“简单”的一些定义:

#!/bin/sh
set -e
for link; do
    test -h "$link" || continue

    dir=$(dirname "$link")
    reltarget=$(readlink "$link")
    case $reltarget in
        /*) abstarget=$reltarget;;
        *)  abstarget=$dir/$reltarget;;
    esac

    rm -fv "$link"
    cp -afv "$abstarget" "$link" || {
        # on failure, restore the symlink
        rm -rfv "$link"
        ln -sfv "$reltarget" "$link"
    }
done

使用链接名称作为参数运行此脚本,例如通过find . -type l -exec /path/tos/script {} +

答案2

如果我理解正确的话,命令-L的标志cp应该完全符合你的要求。

只需复制所有符号链接,它就会用它们指向的文件替换它们:

cp -L file tmp/ && rm file && mv tmp/file .

答案3

可能使用 tar 将数据复制到新目录更容易。

-H      (c and r mode only) Symbolic links named on the command line will
        be followed; the target of the link will be archived, not the
        link itself.

你可以使用类似这样的东西

tar -hcf - sourcedir | tar -xf - -C newdir

tar --help:
-H, --format=FORMAT        create archive of the given format
-h, --dereference          follow symlinks; archive and dump the files they point to

答案4

很可能,“简单”将成为您的一项功能。

我可能会编写一个脚本,使用“find”命令行实用程序查找符号链接文件,然后调用 rm 和 cp 来删除和替换该文件。在移动符号链接之前,最好也让 find 调用的操作检查是否有足够的可用空间。

另一个解决方案可能是通过隐藏符号链接(如 samba)来挂载有问题的文件系统,然后从中复制所有内容。但在很多情况下,这样的做法会引发其他问题。

对你的问题更直接的回答可能是“是”。

编辑:根据要求提供更多具体信息。根据find 的手册页,此命令将列出深度为 2 个目录的所有符号链接文件,从 / 开始:

find / -maxdepth 2 -type l -print

这是在这里发现的

让 find 在找到后执行某些操作:

find / -maxdepth 2 -type l -exec ./ReplaceSymLink.sh {} \;

我相信这会调用我刚刚编写的一些脚本,并传入您刚刚找到的文件名。或者,您可以将查找输出捕获到文件中(使用“find [blah] > symlinks.data”等),然后将该文件传入您编写的脚本中,以优雅地处理原始文件的复制。

相关内容