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

查看:83
本文介绍了如何在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.

如果愿意,您可以仅构建一个使用原始readlink行为实现相同功能的shell脚本.这是一个例子.显然,您可以将其插入您自己的脚本中,在其中您要调用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.

请注意,此脚本希望像./script_name filename一样被调用,不能像-f一样被调用,如果您希望能够与-f filename一起使用,例如GNU readlink,则将$1更改为$2.

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天全站免登陆