Created
May 26, 2020 09:44
-
-
Save seyfahni/475ff9a6f7e58a03308b3bfa39dd4a1e to your computer and use it in GitHub Desktop.
readlink -f on every system
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if ! { [[ $(command -v readlink) ]] && readlink --version | grep -q "GNU coreutils"; } then | |
# not using GNU readlink, so using ... | |
if [[ $(command -v python3) ]]; then | |
# ... python substitute, if python is installed, otherwise ... | |
readlink() { | |
python3 -c 'import os,sys;print(os.path.realpath(sys.argv[1]), end='\'\'')' "$2" | |
} | |
else | |
# ... manual readlink implementation | |
readlink() { | |
( | |
RECURSION_LIMIT=1000 | |
TARGET_FILE="$2" | |
cd "$(dirname "$TARGET_FILE")" | |
TARGET_FILE="$(basename "$TARGET_FILE")" | |
LINK_COUNT=0 | |
# 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")" | |
if test $((LINK_COUNT = LINK_COUNT + 1)) -gt $RECURSION_LIMIT; then | |
exit 1 | |
fi | |
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)" | |
printf "%s/%s" "$PHYS_DIR" "$TARGET_FILE" | |
) | |
} | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment