解决“太多级别的链接”错误
1. 概述
在本文中,我们将了解当我们想要使用链接时如何解决“链接级别过多”错误。
2. 使用ln命令创建链接
要使用ln 命令创建链接 ,我们需要传递*–s* 或*–symbolic*选项:
$ ln -s A B
ln的 GNU 手册将源显示为TARGET,将目标显示为LINK_NAME:
ln [OPTION]... [-T] TARGET LINK_NAME
这种命名约定可能会让一些人感到困惑,因此提醒自己ln就像cp 和mv 可能会有所帮助:源 (A) 需要先出现,然后是目标 (B)。
或者我们可以自然地说:我们正在创建一个到 A 的链接,我们想将其称为 B。
3. 问题:“链接的级别太多”错误
假设我们有以下目录结构:
$ tree --noreport -fp
.
└── [drwxr-xr-x] ./topdir
├── [drwxr-xr-x] ./topdir/source
└── [drwxr-xr-x] ./topdir/outputdir
然后我们创建一个链接,并期望创建的outputdir/source链接将指向source目录:
$ cd /topdir
$ ln -s source outputdir
$ tree --noreport -fp
.
├── [drwxr-xr-x] ./source
└── [drwxr-xr-x] ./outputdir
└── [lrwxrwxrwx] ./outputdir/source -> source
链接已创建,但实际上已损坏。
我们可以使用find 命令找到所有损坏的链接:
$ find -L -xtype l
find: ‘./test/outputdir/source’: Too many levels of symbolic links
此错误的原因是具有相对源的链接始终相对于 symlink 目录,而不是我们创建链接的目录。
因此,我们刚刚创建的链接*/topdir/outputdir/source指向/topdir/outputdir/source而不是/topdir/source*。
让我们看另一个例子。
假设我们有这个目录结构。然后,在我们创建链接后,我们可以检查链接是否正确:
$ cd /topdir
$ tree --noreport -fp
.
└── [drwxr-xr-x] ./test
├── [drwxr-xr-x] ./test/source
└── [drwxr-xr-x] ./test/outputdir
$ ln -s test/source test/outputdir
$ tree --noreport -fp
.
└── [drwxr-xr-x] ./test
├── [drwxr-xr-x] ./test/source
└── [drwxr-xr-x] ./test/outputdir
└── [lrwxrwxrwx] ./test/outputdir/source -> test/source
$ find -L -xtype l
./test/outputdir/source
我们刚刚创建的链接—— /topdir/test/outputdir/source——也被破坏了,因为它指向一个不存在的目录。
它不是指向/topdir/test/source,而是指向*/topdir/test/outputdir/test/source*。**
有两种方法可以解决此问题。让我们看一下接下来的部分。
4. 使用绝对路径
我们可以为source参数使用绝对路径:
$ cd /topdir
$ ln -s "$(pwd)/source" outputdir
$ tree --noreport -fp
.
├── [drwxr-xr-x] ./source
└── [drwxr-xr-x] ./outputdir
└── [lrwxrwxrwx] ./outputdir/source -> /topdir/source
让我们验证链接是否有效:
$ cd /topdir
$ touch /topdir/source/sample.txt
$ tree --noreport -fp
.
├── [drwxr-xr-x] ./source
│ └── [-rw-r--r--] ./source/sample.txt
└── [drwxr-xr-x] ./outputdir
└── [lrwxrwxrwx] ./outputdir/source -> /topdir/source
$ cd outputdir/source
$ ls -l
total 0
-rw-r--r-- 1 blogdemo blogdemo 0 Aug 3 20:51 sample.txt
正如我们在上面看到的,我们已经成功地使用链接来访问source目录并列出所有文件。
对绝对路径进行链接的缺点是当目录名称更改时它们很容易被破坏。
5. 使用相对路径
另一种解决错误的方法是使用source参数的相对路径:
$ cd /topdir
$ ln -s ../source outputdir
$ tree --noreport -fp
.
├── [drwxr-xr-x] ./source
│ └── [-rw-r--r--] ./source/sample.txt
└── [drwxr-xr-x] ./outputdir
└── [lrwxrwxrwx] ./outputdir/source -> ../source
$ ls outputdir/source -l
lrwxrwxrwx 1 blogdemo blogdemo 9 Aug 3 21:11 outputdir/source -> ../source
我们可以使用ln命令的*-r* 或*–relative选项来自动生成source*路径:
$ cd /topdir
$ ln -sr source outputdir
$ tree --noreport -fp
.
├── [drwxr-xr-x] ./source
│ └── [-rw-r--r--] ./source/sample.txt
└── [drwxr-xr-x] ./outputdir
└── [lrwxrwxrwx] ./outputdir/source -> ../source
$ ls outputdir/source -l
lrwxrwxrwx 1 blogdemo blogdemo 9 Aug 3 21:11 outputdir/source -> ../source
我们已成功使用链接访问source目录并列出所有文件。