Last active
December 19, 2015 08:19
-
-
Save benevans/5925018 to your computer and use it in GitHub Desktop.
Finds the real path of a possibly symlinked pathname.
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
#!/usr/bin/env bash | |
# Adapted from Maven's mvn script. | |
# Given a path possibly containing symlinks, work back to get the | |
# real path. Useful when a script needs to derive its base dir from | |
# $(dirname $0), but $0 is a symlink to the real script. | |
canonical_path() { | |
local path="$1" | |
while [ -L "$path" ]; do | |
local link="$(expr "$(ls -ld "$path")" : '.*-> \(.*\)$')" | |
if expr "$link" : '/.*' >/dev/null 2>&1; then | |
path="$link" # absolute path in link | |
else | |
path="$(dirname "$path")/$link" | |
fi | |
done | |
local dir | |
dir="$(cd -P "$(dirname "$path")" >/dev/null 2>&1 && pwd)" | |
if [ $? -ne 0 ]; then | |
echo $1 # fail - just echo the original and try to carry on | |
return 1 | |
fi | |
echo $dir/$(basename "$path") | |
} | |
# example usage: | |
BASEDIR="$(dirname $(canonical_path "$0"))" | |
# Now we have the real basedir, even if we were invoked as /usr/bin/foo etc. | |
if [ -f "$BASEDIR/foo.conf" ]; then ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment