假设我设置了一个符号链接:
ln -s /root/Public/mytextfile.txt /root/Public/myothertextfile.txt
有没有办法看到myothertextfile.txt
的目标是使用命令行?
编辑:使用'-f'标志打印规范化的版本。
readlink -f /root/Public/myothertextfile.txt
man readlink ... -f, --canonicalize canonicalize by following every symlink in every component of the given name recursively; all but the last component must exist
readlink是你想要的命令。 你应该看看命令的手册页。 因为如果你想遵循一连串的符号链接到实际的文件,那么你需要-e或-f开关:
$ ln -s foooooo zipzip # fooooo doesn't actually exist $ ln -s zipzip zapzap $ # Follows it, but doesn't let you know the file doesn't actually exist $ readlink -f zapzap /home/kbrandt/scrap/foooooo $ # Follows it, but file not there $ readlink -e zapzap $ # Follows it, but just to the next symlink $ readlink zapzap zipzip
这也将工作:
ls -l /root/Public/myothertextfile.txt
但是readlink
会被用在脚本中而不是parsingls
。
如果要显示链接的来源和目的地,请尝试stat -c%N files*
。 例如
$ stat -c%N /dev/fd/* '/dev/fd/0' -> '/dev/pts/4' '/dev/fd/1' -> '/dev/pts/4'
这不利于parsing(使用readlink
),但它显示链接名称和目的地,没有ls -l
的混乱
-c
可以写成--format
, %N
表示“带引号的文件名,如果有符号链接,则取消引用”。
readlink
是一件好事,但是GNU特有的和非跨平台的。 我曾经为/bin/sh
编写跨平台脚本,因此我会使用如下所示的内容:
ls -l /root/Public/myothertextfile.txt | awk '{print $NF}'
要么:
ls -l /root/Public/myothertextfile.txt | awk -F"-> " '{print $2}'
但是这些需要在不同的平台上进行testing。 我认为他们会工作,但不是100%确定为ls
输出格式。
如果你不能使用readlink
,那么parsingls -l
的结果可以像这样完成。
正常的结果是:
ls -l /root/Public/myothertextfile.txt lrwxrwxrwx 1 root root 30 Jan 1 12:00 /root/Public/myothertextfile.txt -> /root/Public/mytextfile.txt
所以我们想要在“ – >”和包括箭头之前replace所有的东西。 我们可以使用sed
来实现这个function:
ls -l /root/Public/myothertextfile.txt | sed 's/^.* -> //' /root/Public/mytextfile.txt