Looking for POSIX utility to test whether filename is a symlink

posixsymlink

I know that some shells at least support file test operators that detect when a filename names a symlink.

Is there a POSIX utility1 that provides the same functionality?


1 I may not be using the right terminology here. What I mean by "utility" is a free-standing executable living somewhere under /bin, /usr/bin, etc., as opposed to a shell built-in.

Best Answer

You're looking for test:

-h pathname

True if pathname resolves to a file that exists and is a symbolic link. False if pathname cannot be resolved, or if pathname resolves to a file that exists but is not a symbolic link. If the final component of pathname is a symlink, that symlink is not followed.

Most shells have it as a builtin, but test also exists as a standalone program, which can be called from other programs without invoking an intermediate shell. This is the case for most builtins that shells may have, except for those that act on the shell itself (special builtins like break, export, set, …).

[ -h pathname ] is equivalent to test -h pathname; [ works in exactly the same way as test, except that [ requires an extra ] argument at the end. [, like test, exists as a standalone program.

For example:

$ ln -s foo bar
$ /usr/bin/test -h bar && echo y
y