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

2

61

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?

Oireachtas answered 18/7, 2010 at 16:56 Comment(1)
Something related was also asked on the Unix & Linux SE.Freesia
W
97
readlink -f <linkname>

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

Which answered 18/7, 2010 at 16:58 Comment(2)
I didn't use the -f option in mac because it gave me an error readlink: illegal option -- fPathogenic
@JonathanMoralesVélez - that only matters if you have a link to another link and want the final non-symlink file. If that matters, install Homebrew and use the GNU version of readlink.Which
P
6
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
...
Pisano answered 31/10, 2018 at 10:53 Comment(1)
Important not to include a closing /, i.e. stat /usr/local/cuda, not stat /usr/local/cuda/.Matriculation

© 2022 - 2024 — McMap. All rights reserved.