如何在 bash 中取消引用符号链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1197690/
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-09 18:21:18  来源:igfitidea点击:

How can I derefence symbolic links in bash?

bashsymlink

提问by David Dean

How can I take any given path in bashand convert it to it's canonical form, dereferencing any symbolic links that may be contained within the path?

我怎样才能将任何给定的路径bash转换为它的规范形式,取消引用路径中可能包含的任何符号链接?

For example:

例如:

~$ mkdir /tmp/symtest
~$ cd /tmp/symtest/
/tmp/symtest$ mkdir -p foo/bar cat/dog
/tmp/symtest$ cd foo/bar/
/tmp/symtest/foo/bar$ ln -s ../../cat cat
/tmp/symtest/foo/bat$ cd ../../
/tmp/symtest$ tree
.
|-- cat
|   `-- dog
`-- foo
    `-- bar
       `-- cat -> ../../cat

6 directories, 0 files

How can I get the full canonical path of /tmp/symtest/foo/bar/cat(i.e: /tmp/symtest/cat)?

我怎样才能获得/tmp/symtest/foo/bar/cat(即:)的完整规范路径/tmp/symtest/cat

回答by David Dean

Thanks to Andy Skelton, it appears the answer is readlink -f:

感谢Andy Skelton,答案似乎是readlink -f

$:/tmp/symtest$ readlink -f /tmp/symtest/foo/bar/cat
/tmp/symtest/cat

回答by usbdongle

Here's a function that will resolve symbolic links
It's original purpose is to resolve the full path to the calling script pointed to by a /usr/bin symlink

这是一个将解析符号链接的函数
它的原始目的是解析 /usr/bin 符号链接指向的调用脚本的完整路径

# resolve symbolic links
function resolve_link() {
  local LINK_FILE=${1:-${BASH_SOURCE[0]}}
  local FILE_TYPE=`file $LINK_FILE | awk '{print }'`
  local LINK_TO=$LINK_FILE
  while [ $FILE_TYPE = "symbolic" ]; do
    LINK_TO=`readlink $LINK_FILE`
    FILE_TYPE=`file $LINK_TO | awk '{print }'`
  done
  echo $LINK_TO
}

BASH_SOURCE_RESOLVED=$(resolve_link)
echo $BASH_SOURCE_RESOLVED

It doesn't use recursion but then again I've never used recursion in bash

它不使用递归,但我从来没有在 bash 中使用过递归