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?

  • 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

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"))
| 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.

| improve this answer | |

one line:

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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