In Bash, how do I safely determine what a soft link points to?

BashSymlink

Bash Problem Overview


I need to process a number of directories, determine what files in them are symlinks, and what they link to. This sounds simple, but I have no control over the presence of control or other characters in the file names, and I need a robust solution.

So, given a file of arbitrary name, how do I safely determine what it links to, when the link destination can also have arbitrary contents?

Bash Solutions


Solution 1 - Bash

readlink -f <linkname>

See the readlink(1) man page for Linux, FreeBSD, NetBSD, OpenBSD, DragonFly or the GNU coreutils info page.

Solution 2 - Bash

stat <linkname>

Example:

stat /usr/local/cuda

First 2 lines will give:

File: '/usr/local/cuda' -> 'cuda-8.0'
Size: 8         	Blocks: 0          IO Block: 4096   symbolic link
...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionswestrupView Question on Stackoverflow
Solution 1 - BasheduffyView Answer on Stackoverflow
Solution 2 - BashKonstantinos RoditakisView Answer on Stackoverflow