Differences between revisions 1 and 5 (spanning 4 versions)
Revision 1 as of 2009-02-10 14:57:37
Size: 590
Editor: GreyCat
Comment: How do I determine whether a symlink is dangling (broken)?
Revision 5 as of 2012-01-13 09:52:29
Size: 1054
Editor: ght
Comment: add link to FAQ031 (difference between test, [, [[)
Deletions are marked like this. Additions are marked like this.
Line 3: Line 3:
The documentation on this is fuzzy, but it turns out you ''can'' do this with bash builtins: The documentation on this is fuzzy, but it turns out you ''can'' do this with shell builtins:
Line 7: Line 7:
if [[ -L $symlink && ! -e $symlink ]]; then
 
echo "$symlink is dangling"
if [[ ( -L $name ) && ( ! -e $name ) ]]
then echo "$name is a dangling symlink"
Line 12: Line 12:
The `-e` test (like all other tests besides `-L` or `-h`) follows the symbolic link, and therefore it checks on the thing ''pointed to'', not on the link itself. The `-L` test does not follow the symlink, so it's checking on the link itself. Together, they can indicate the presence of a dangling symlink. 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 [[BashFAQ/031|(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
}}}

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)