在 Bash 中,如何安全地确定软链接指向的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3276403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:21:00  来源:igfitidea点击:

In Bash, how do I safely determine what a soft link points to?

bashsymlink

提问by swestrup

I need to process a number of directories, determine what files in them are symlinks, and what they link to. This sounds simple, but I have no control over the presence of control or other characters in the file names, and I need a robust solution.

我需要处理多个目录,确定其中的哪些文件是符号链接,以及它们链接到的内容。这听起来很简单,但我无法控制文件名中是否存在控件或其他字符,我需要一个强大的解决方案。

So, given a file of arbitrary name, how do I safely determine what it links to, when the link destination can also have arbitrary contents?

那么,给定一个任意名称的文件,当链接目的地也可以包含任意内容时,我如何安全地确定它链接到的内容?

回答by eduffy

readlink -f <linkname>

readlink -f <linkname>

See man 1 readlink

man 1 readlink

回答by Konstantinos Roditakis

stat <linkname>

Example:

例子:

stat /usr/local/cuda

First 2 lines will give:

前两行将给出:

File: '/usr/local/cuda' -> 'cuda-8.0'
Size: 8             Blocks: 0          IO Block: 4096   symbolic link
...

回答by Sero

Python 2 script that traces/follows symbolic links provided as arguments.

跟踪/跟踪作为参数提供的符号链接的 Python 2 脚本。

listSymLink.py

listSymLink.py

import os.path as OSPath
import os
import sys

for arg in sys.argv[1:]:
    if OSPath.exists(arg):
        pathTrail = [OSPath.abspath(arg)]
        while OSPath.islink(pathTrail[-1]):
            linkTarget = os.readlink(pathTrail[-1])
            if not OSPath.isabs(linkTarget):
                linkTarget = OSPath.join(os.path.dirname(pathTrail[-1]), linkTarget)
            pathTrail.append(linkTarget)
        print " -> ".join(map(lambda x: "\"" + x + "\"", pathTrail))
    else:
        print "\"" + arg + "\" path doesn't exist"

Example

例子

python listSymLink.py /usr/bin/c++

prints

印刷

"/usr/bin/c++" -> "/etc/alternatives/c++" -> "/usr/bin/g++" -> "/usr/bin/g++-8" -> "/usr/bin/x86_64-linux-gnu-g++-8"