Real Path of a Symbolic Link
03 May, 2010
I needed to figure out the real path of a symbolic link to a file for a script so that i could set the parent dir of the file as home.
The file (ec2-version) was linked into /usr/local/bin but I needed the path to ec2-tools home.
# filename : realpath
# which file is found in the exec path
binpath=$(which $1)
# ls -l gives
# lrwxr-xr-x 1 briandemant wheel 49 Mar 5 11:32 \
# /usr/local/bin/ec2-version -> ../ec2-api-tools/bin/ec2-version
# I only need the last after '-> '
realfile=$(ls -l $binpath | egrep -o "[^> ]+$")
# as the link can be relative we need to be in the link dir
cd $(dirname $binpath)
# and from there go to the dir of the realfile
cd $(dirname $realfile)
# now we can return the fullpath to the real file
echo $(pwd)/$1