Differences between revisions 5 and 6
Revision 5 as of 2012-01-13 09:52:29
Size: 1054
Editor: ght
Comment: add link to FAQ031 (difference between test, [, [[)
Revision 6 as of 2016-10-29 17:13:52
Size: 1046
Editor: jaffer
Comment:
Deletions are marked like this. Additions are marked like this.
Line 7: Line 7:
if [[ ( -L $name ) && ( ! -e $name ) ]] if [[ -L $name && ! -e $name ]]

The documentation on this is fuzzy, but it turns out you can do this with shell builtins:

# Bash
if [[ -L $name && ! -e $name ]]
then echo "$name is a dangling symlink"
fi

The Bash man page tells you that "-L" returns "True if file exists and is a symbolic link", and "-e" returns "True if file exists". What might not be clear is that "-L" considers "file" to be the link itself. To "-e", however, "file" is the target of the symlink (whatever the link is pointing to). That's why you need both tests to see if a symlink is dangling; "-L" checks the link itself, and "-e" checks whatever the link is pointing to.

POSIX has these same tests, with similar semantics, so if for some reason you can't use the (preferred) [[ command, the same test can be done using the older [ command:

# POSIX
if [ -L "$name" ] && [ ! -e "$name" ]
then echo "$name is a dangling symlink"
fi

BashFAQ/097 (last edited 2016-10-29 17:13:52 by jaffer)