Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the behavior of GNU's readlink -f on a Mac?

Tags:

sh

macos

freebsd

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?

Here's some debug information:

$ which readlink; readlink -f /usr/bin/readlink readlink: illegal option -f usage: readlink [-n] [file ...] 
like image 572
troelskn Avatar asked Jun 28 '09 20:06

troelskn


2 Answers

MacPorts and Homebrew provide a coreutils package containing greadlink (GNU readlink). Credit to Michael Kallweitt post in mackb.com.

brew install coreutils  greadlink -f file.txt 
like image 190
tomyjwu Avatar answered Oct 16 '22 02:10

tomyjwu


readlink -f does two things:

  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.

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 

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.

EDITED to use pwd -P instead of $PWD.

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.

like image 42
Keith Smith Avatar answered Oct 16 '22 02:10

Keith Smith