HomeSoftwareGamesMusicForum

Get link target

Where does a symbolic link point to? This sounds like a silly question, as the target can easily be shown using the command ls -l. However, things aren't always that simple. The target shown by this command is the the direct target, which again may be a symbolic link, pointing to another link, and so on. Actually any file name can represent a link chain of arbitrary length. Which real file this chain eventually points to can't be deduced from the ls output.

Many systems provide a command readlink, which, if called with the option -e, prints the final link target. If your system lacks this command, you can try the following function getlink. Usage:

getlink [-l] path

Without an option, it prints the direct target, similar to ls -l. If path is not a link, the parameter itself is printed. With option -l, the link chain starting with path is followed to its end and the final target is printed. The return code is 0 if all targets exist, 1 otherwise.

All paths are printed in normalized form, i.e. they don't contain components consisting of one ore two dots. [1]


[1] Thanks to Greg Wooledge for some hints how to handle unsane file names like 'a->b' or names with trailing newlines

up
Created 2011-08-11 by mopcoge