如何在 Mac 上获得 GNU 的 readlink -f 的行为? [英] How can I get the behavior of GNU's readlink -f on a Mac?

查看:24
本文介绍了如何在 Mac 上获得 GNU 的 readlink -f 的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On Linux, the readlink utility accepts an option -f that follows additional links. This doesn't seem to work on Mac and possibly BSD based systems. What would the equivalent be?

以下是一些调试信息:

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

推荐答案

readlink -f 做了两件事:

  1. 它沿着一系列符号链接迭代,直到找到一个实际的文件.
  2. 它返回该文件的规范化名称——即它的绝对路径名.
  1. It iterates along a sequence of symlinks until it finds an actual file.
  2. It returns that file's canonicalized name—i.e., its absolute pathname.

如果你愿意,你可以构建一个 shell 脚本,它使用普通的 readlink 行为来实现同样的事情.这是一个例子.显然,您可以将其插入到您想调用 readlink -f

If you want to, you can just build a shell script that uses vanilla readlink behavior to achieve the same thing. Here's an example. Obviously you could insert this in your own script where you'd like to call 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

请注意,这不包括任何错误处理.特别重要的是,它不会检测符号链接循环.一个简单的方法是计算你绕过循环的次数,如果你遇到一个不可能的大数字,比如 1,000,就会失败.

Note that this doesn't include any error handling. Of particular importance, it doesn't detect symlink cycles. A simple way to do this would be to count the number of times you go around the loop and fail if you hit an improbably large number, such as 1,000.

编辑使用 pwd -P 而不是 $PWD.

EDITED to use pwd -P instead of $PWD.

注意这个脚本期望像./script_name filename一样被调用,没有-f,把$1改为$2 如果你想像 GNU readlink 一样使用 -f 文件名.

Note that this script expects to be called like ./script_name filename, no -f, change $1 to $2 if you want to be able to use with -f filename like GNU readlink.

这篇关于如何在 Mac 上获得 GNU 的 readlink -f 的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆