在Linux上,readlink实用程序接受附加链接后面的选项-f。这似乎不适用于Mac和基于BSD的系统。等价的是什么?

下面是一些调试信息:

$ which readlink; readlink -f
/usr/bin/readlink
readlink: illegal option -f
usage: readlink [-n] [file ...]

当前回答

Readlink -f做两件事:

它沿着符号链接序列迭代,直到找到一个实际的文件。 它返回该文件的规范化名称。,它的绝对路径名。

如果您愿意,您可以构建一个shell脚本,使用普通readlink行为来实现相同的功能。举个例子。显然,你可以在自己的脚本中插入这个,你想调用readlink -f

#!/bin/sh

TARGET_FILE=$1

cd `dirname $TARGET_FILE`
TARGET_FILE=`basename $TARGET_FILE`

# Iterate down a (possible) chain of symlinks
while [ -L "$TARGET_FILE" ]
do
    TARGET_FILE=`readlink $TARGET_FILE`
    cd `dirname $TARGET_FILE`
    TARGET_FILE=`basename $TARGET_FILE`
done

# Compute the canonicalized name by finding the physical path 
# for the directory we're in and appending the target file.
PHYS_DIR=`pwd -P`
RESULT=$PHYS_DIR/$TARGET_FILE
echo $RESULT

注意,这并不包括任何错误处理。特别重要的是,它不检测符号链接循环。一种简单的方法是计算循环的次数,如果碰到一个不太可能的大数字(比如1000),就会失败。

edit使用pwd -P而不是$ pwd。

注意,这个脚本希望被称为。/script_name文件名,不使用-f,如果你想能够像GNU readlink一样使用-f文件名,将$1更改为$2。

其他回答

开始更新

This is such a frequent problem that we have put together a Bash 4 library for free use (MIT License) called realpath-lib. This is designed to emulate readlink -f by default and includes two test suites to verify (1) that it works for a given unix system and (2) against readlink -f if installed (but this is not required). Additionally, it can be used to investigate, identify and unwind deep, broken symlinks and circular references, so it can be a useful tool for diagnosing deeply-nested physical or symbolic directory and file problems. It can be found at github.com or bitbucket.org.

最后更新

另一个非常紧凑和高效的解决方案,它只依赖于Bash:

function get_realpath() {

    [[ ! -f "$1" ]] && return 1 # failure : file does not exist.
    [[ -n "$no_symlinks" ]] && local pwdp='pwd -P' || local pwdp='pwd' # do symlinks.
    echo "$( cd "$( echo "${1%/*}" )" 2>/dev/null; $pwdp )"/"${1##*/}" # echo result.
    return 0 # success

}

这还包括一个环境设置no_symlinks,它提供了将符号链接解析到物理系统的能力。只要no_symlinks被设置为某个值,即no_symlinks='on',那么symlinks将被解析为物理系统。否则将应用它们(默认设置)。

这应该可以在任何提供Bash的系统上工作,并将返回一个与Bash兼容的退出代码用于测试。

一个简单的perl单行程序,几乎可以在任何地方工作,没有任何外部依赖:

perl -MCwd -e 'print Cwd::abs_path shift' ~/non-absolute/file

将解除对符号链接的引用。

脚本中的用法可能是这样的:

readlinkf(){ perl -MCwd -e 'print Cwd::abs_path shift' "$1";}
ABSPATH="$(readlinkf ./non-absolute/file)"

实现

安装酿造

按照https://brew.sh/上的说明操作

安装coreutils包

酿造安装coreutils

创建别名或符号链接

3 a。创建一个别名(每个用户)

您可以将别名放在~/中。bashrc,(~ /。Bash_profile,或者任何您习惯保存bash别名的地方。我个人把我的文件保存在~/.bashrc中

别名指向= greadlink

3 b。创建一个符号链接(系统范围)

ln -s /usr/local/bin/greadlink /usr/local/bin/readlink(来源:Izana)

这将在/usr/local/bin中创建一个符号链接,同时保留原始的readlink二进制文件。它可以工作,因为搜索readlink将返回2个结果。但是/usr/local/bin中的第二个将优先。

例如,哪个readlink

要撤消此更改,只需取消link /usr/local/bin/readlink

额外的工具

您可以为其他coreutil创建类似的别名或符号链接,例如gmv、gdu、gdf等等。但是要注意,GNU在mac机器上的行为可能会让其他习惯使用本机coreutils的人感到困惑,或者在mac系统上可能会以意想不到的方式表现。

解释

coreutils是一个brew包,用于安装GNU/Linux核心实用程序,这些实用程序对应于Mac OSX实现,以便您可以使用它们

你可能会发现mac osx系统上的程序或实用程序看起来与Linux coreutils(“核心实用程序”)相似,但它们在某些方面有所不同(例如具有不同的标志)。

这是因为Mac OSX对这些工具的实现是不同的。要获得原始的类似GNU/ linux的行为,您可以通过brew包管理系统安装coreutils包。

这将安装相应的核心实用程序,前缀为g。例如,对于readlink,你将找到相应的greadlink程序。

为了使readlink执行起来像GNU readlink (greadlink)实现,您可以在安装coreutils后创建一个简单的别名或符号链接。

由于使用非bsd Linux和macOS的人都使用我的工作,所以我选择在构建脚本中使用这些别名(包括sed,因为它有类似的问题):

##
# If you're running macOS, use homebrew to install greadlink/gsed first:
#   brew install coreutils
#
# Example use:
#   # Gets the directory of the currently running script
#   dotfilesDir=$(dirname "$(globalReadlink -fm "$0")")
#   alias al='pico ${dotfilesDir}/aliases.local'
##

function globalReadlink () {
  # Use greadlink if on macOS; otherwise use normal readlink
  if [[ $OSTYPE == darwin* ]]; then
    greadlink "$@"
  else
    readlink "$@"
  fi
}

function globalSed () {
  # Use gsed if on macOS; otherwise use normal sed
  if [[ $OSTYPE == darwin* ]]; then
    gsed "$@"
  else
    sed "$@"
  fi
}

可选检查,您可以添加自动安装homebrew + coreutils依赖项:

if [[ "$OSTYPE" == "darwin"* ]]; then
  # Install brew if needed
  if [ -z "$(which brew)" ]; then 
    /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"; 
  fi
  # Check for coreutils
  if [ -z "$(brew ls coreutils)" ]; then
    brew install coreutils
  fi
fi

我想要真正做到“全球化”,它需要检查其他国家……但这可能接近80/20的标记。

您可能既需要可移植的纯shell实现,也需要单元测试覆盖率,因为此类情况的边缘情况的数量非常多。

查看我的项目在Github上的测试和完整代码。下面是实现的概要:

正如Keith Smith敏锐地指出的那样,readlink -f做了两件事:1)递归地解析符号链接,2)规范化结果,因此:

realpath() {
    canonicalize_path "$(resolve_symlinks "$1")"
}

首先,符号链接解析器实现:

resolve_symlinks() {
    local dir_context path
    path=$(readlink -- "$1")
    if [ $? -eq 0 ]; then
        dir_context=$(dirname -- "$1")
        resolve_symlinks "$(_prepend_path_if_relative "$dir_context" "$path")"
    else
        printf '%s\n' "$1"
    fi
}

_prepend_path_if_relative() {
    case "$2" in
        /* ) printf '%s\n' "$2" ;;
         * ) printf '%s\n' "$1/$2" ;;
    esac 
}

请注意,这是完整实现的略微简化版本。完整的实现为符号链接循环添加了一个小检查,并对输出进行了一些处理。

最后,规范化路径的函数:

canonicalize_path() {
    if [ -d "$1" ]; then
        _canonicalize_dir_path "$1"
    else
        _canonicalize_file_path "$1"
    fi
}   

_canonicalize_dir_path() {
    (cd "$1" 2>/dev/null && pwd -P) 
}           
        
_canonicalize_file_path() {
    local dir file
    dir=$(dirname -- "$1")
    file=$(basename -- "$1")
    (cd "$dir" 2>/dev/null && printf '%s/%s\n' "$(pwd -P)" "$file")
}

差不多就是这样。简单到可以粘贴到您的脚本中,但也非常棘手,如果您依赖于任何用例中没有单元测试的代码,那就太疯狂了。