Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
up vote 4 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 – Dan Rosenstark Aug 21 '12 at 21:12
also for directories I removed the dirname() piece. – Dan Rosenstark Aug 21 '12 at 21:43

This would work.

cd_link ()
    [ ! -L "$LINK" ] && return;
    DIR=$(readlink "$LINK");
    cd $DIR

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

share|improve this answer

one line:

cd $(dirname $([ -L $0 ] && readlink -f $0 || echo $0))
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .