Unix – How to get a list of symbolic links, excluding broken links

symlinkunix

I have been able to find a command to get a list of the broken links only, but not the "working" symbolic links

find -H mydir -type l

How can I do the opposite?

If I have these files in mydir:

foo
bar
bob
carol

If they are all symbolic links, but bob points to a file that doesn't exist, I want to see

foo
bar
carol

Best Answer

With find(1) use

$ find . -type l -not -xtype l

This command finds links that stop being links after following - that is, unbroken links. (Note that they may point to ordinary or special files, directories or other. Use -xtype f instead of -not -xtype l to find only links pointing to ordinary files.)

$ find . -type l -not -xtype l -ls

reports where they point to.

If you frequently encounter similar questions in your interactive shell usage, zsh is your friend:

% echo **/*(@^-@)

which follows the same idea: Glob qualifier @ restricts to links, and ^-@ means "not (^) a link (@) when following is enabled (-).

(See also this post about finding broken links in python, actually this demonstrates what you can do in all languages under Linux. See this blog post for a complete answer to the related question of "how to find broken links".)

Related Topic