How can I get the behavior of GNU's readlink -f on a Mac? [closed]
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
readlink -f
does two things:
- It iterates along a sequence of symlinks until it finds an actual file.
- 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.