Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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?

share|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
add comment

2 Answers

up vote 3 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"))
}
share|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
    
great, under zsh on mac I'm using it without the -f but it seems to work +1 –  Yar Aug 21 '12 at 21:12
    
also for directories I removed the dirname() piece. –  Yar Aug 21 '12 at 21:43
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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