1

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?

2
  • 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. Jan 11, 2011 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, 2011 at 23:01

3 Answers 3

4

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"))
}
3
  • 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, 2011 at 23:30
  • great, under zsh on mac I'm using it without the -f but it seems to work +1 Aug 21, 2012 at 21:12
  • also for directories I removed the dirname() piece. Aug 21, 2012 at 21:43
1

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.

0

one line:

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

You must log in to answer this question.

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