linuxbashsymlinksymlink-traversal

How do you list all symlinks in a directory that has non-hanging links?


I would like to get a list of all symlinks within a directory that has valid links. In other words, I would like all the broken links to be discarded in my list.


Solution

  • In shell, [ -L "$f" ] && [ -e "$f" ] is true if and only if "$f" is the name of a symlink whose target exists. So:

    for f in *; do
        if [ -L "$f" ] && [ -e "$f" ]; then
            # do something with "$f"
        fi
    done
    

    (Never use the -a or -o options to test/[...]; they cannot be relied on to have sane precedence.)