On a UNIX machine I in my current directory I create a symbolic link:

> ln -s public_html/code/index.html

Which creates a file locally named index.html. How can cd to the directory public_html/code from the soft link file?

link|improve this question

What's the reason for this? If you really need to be able to get to the directory holding index.html, perhaps you should create the soft link to that directory, which will let you cd to it. – Harper Shelby Jan 11 '11 at 22:57
@ Harper - I agree, but often times I've forgotten to do just that and simply link to the file instead of a directory. I then get the directory name from an ls and copy and paste that into the command line, clearly not optimal. – Hooked Jan 11 '11 at 23:01
feedback

2 Answers

up vote 2 down vote accepted

In a sh-like environment:

cd $(dirname $(readlink -f path/to/link))

you can put it in a function:

function cdl
{
    cd $(dirname $(readlink -f "$1"))
}
link|improve this answer
readlink! Awesome, I didn't even know it existed! Accepted this answer over Rich's due to the simplicity, both were great. – Hooked Jan 11 '11 at 23:30
feedback

This would work.

cd_link ()
{
    LINK="$1";
    [ ! -L "$LINK" ] && return;
    DIR=$(readlink "$LINK");
    DIR=${DIR%/*};
    cd $DIR
}

This needs to be a function, not a script. Put in your .bashrc, .kshrc, etc.

link|improve this answer
feedback

Your Answer

 
or
required, but never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.