-   Linux - Software (
-   -   How to find symlink target name in script (

germanyzulu 09-19-2005 03:39 PM

How to find symlink target name in script

I have a symlink
that points to

I am looking for a command kind of like this:


(From the 'ls' manpage)
-L, --dereference
when showing file information for a symbolic link, show informa-
tion for the file the link references rather than for the link

$ ls -l ~/bin/foo/
lrwx------  1 me me 39 Sep 19 11:47 ~/bin/foo/ -> ~/photos/image.jpg
$ ls -l --dereference ~/bin/foo/
-rwx------  1 me me 150108 May 29  2003 ~/bin/foo/

But I want the name of the target file not just info about it. The 'file' command would work fine except that I don't know how to pull out just the filename for my script, grep with a regex just lists the whole line.

Is there a command you know of/option to 'ls' ?? Or is 'sed'/'awk' something I should look into??


macemoneta 09-19-2005 04:15 PM

file somefile | awk '{print $5}'


ls -l somefile | awk '{print $11}'

germanyzulu 09-19-2005 09:41 PM


That's exactly what I needed.

I suppose I could have read the 'awk' man page but at the time it seemed so daunting, at least now I understand the basics of it.

Thank you!

P.S. There you go Jeremy (and macemoneta) yet another satified Linux user, at least untill I come up with another Question! :)

germanyzulu 08-09-2006 04:14 PM

Well after a long time of not thinking about this I was poking around and found the readlink command:


$readlink --help
Usage: readlink [OPTION]... FILE
Display value of a symbolic link on standard output.

The awk method does work and for more that just the question I had. But for finding the target of a symlink I think this works better. (Much simpler, easyer to read, remember what it does in a script, etc.)

Also it is contained in the coreutils package (Ubuntu) so most if not all distros will have it.

pcabrera 08-14-2015 11:23 AM

One more reason to use readlink is that it can follow recursively
I know is an extremely old thread, but hey, some of these tips are still valid after years!!!

I just wanted to point out one advantage of using readlink instead of the awk solution is that readlink can follow links recursively as opposed to the awk solution.
for example, I found this thread trying to find a way to get the real java command in my system (in a script), so I ended up doing this:


readlink -f $(which java)
Which in fact has two symlinks:


which java -> /usr/bin/java
/usr/bin/java --symlink--> /etc/alternatives/java
/etc/alternatives/java --symlink--> /usr/lib/jvm/jdk1.8.0_11/bin/java

All times are GMT -5. The time now is 01:52 PM.