Soft link pathname conversion for Linux and Unix

Steven W. Orr steveo at syslang.net
Sat Apr 28 19:43:20 UTC 2007


On Saturday, Apr 28th 2007 at 19:42 +0100, quoth John Horne:

=>Hi,
=>
=>I have a shell problem that I am trying to easily resolve. If I have a
=>directory with a soft (symbolic) link in it such as:
=>
=>         fred -> ../bin/csh
=>
=>How can I convert the '../bin/csh' in to a full pathname? Is there a
=>command to do this that will work for Linux and Unices? I need it to
=>work for all circumstances, not just this one particular example. So
=>something like '../../abc/../def' should also work in being converted.
=>
=>Under Linux the 'readlink -f' command works fine, but NetBSD readlink
=>doesn't have the '-f' option, and Solaris doesn't have readlink. I do
=>not want to change directory at all, so changing to the link directory
=>and issuing 'pwd' isn't what I want to do.
=>
=>My only other thought is to process the link pathname bit-by-bit.
=>Preceed the pathname with the current working directory and then remove
=>any './' and jiggle (!) with any '../' to get the directory above. It's
=>messy and could get complicated. Better ideas welcome :-)

First you need to see if the symlink is pointing to a file or a directory. 
You can use -f or -d to see

if [[ -f fred ]]
then
    # do file stuff
elif [[ -d fred ]]
    # do dir stuff

In the file stuff section of your frozen food aisle, find out what fred 
points to.

symval=$(ls -l fred | awk '{print $11}')

Now, knowing that fred is a file, you can remove the file part of the 
symval, thus leaving you with the directory portion:

dirpart=${symval%/*}

Next you could cd there and do a pwd to see where you land:

cd $dirpart; pwd

But wait! How do I get pack and how do I get back knowing where I was on 
my little adventure?

abspath=$(cd $dirpart; pwd)

Use the force Luke!

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net




More information about the users mailing list