Magnus
Magnus

Reputation: 3722

How to follow multiple symlinks to original file on unix/linux?

I sometimes want to know where an original/real file is on my system that is linked via multiple symlinks to a known handle. Running ls -l /path/to/file will show me the location of the next link, but if I want to track down the original then I find myself copy-pasting a bunch of paths, which is cumbersome.

Is there a more direct way (viz. single shortish command) to go straight from A to Z? Or do I have to build a function that sequentially works through each link till we reach the final 'real' file? (Suggestions for such a function are welcome!)

Example case: I wanted to find all of the postgresql executables installed together on centos. To do that, I had to burrow down the following rabbit hole:

which psql
> /usr/bin/psql
ls -l /usr/bin/psql 
> l.......... ... /usr/bin/psql -> /etc/alternatives/pgsql-psql*
ls -l /etc/alternatives/pgsql-psql
> l.......... ...  /etc/alternatives/pgsql-psql -> /usr/pgsql-11/bin/psql*
ls -l /usr/pgsql-11/bin/psql
> -.......... ... /usr/pgsql-11/bin/psql*
ls /usr/pgsql-11/bin/
> [Voila!]

Is there an easier (and generalizable) way to get from psql -> /usr/pgsql-11/bin/?

Upvotes: 3

Views: 412

Answers (1)

that other guy
that other guy

Reputation: 123550

You can use realpath to recursively resolve all symlinks and give you a canonical path:

$ cd /tmp
$ touch baz
$ ln -s baz bar
$ ln -s bar foo

$ ls -l foo
lrwxrwxrwx 1 me me 3 Nov 20 09:42 foo -> bar

$ realpath foo
/tmp/baz

Upvotes: 4

Related Questions