Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

unix

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/?

like image 690
Magnus Avatar asked Nov 17 '25 11:11

Magnus


1 Answers

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
like image 174
that other guy Avatar answered Nov 19 '25 05:11

that other guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!