Differences between revisions 1 and 2
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 2 as of 2009-02-10 15:05:49
Size: 795
Editor: GreyCat
Comment: POSIX too
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 13: Line 13:

POSIX has these same tests, with the same semantics, so it can also be done with the `[` command:

{{{
# POSIX
if [ -L "$symlink" -a ! -e "$symlink" ]; then
  echo "$symlink is dangling"
fi
}}}

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

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

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.

POSIX has these same tests, with the same semantics, so it can also be done with the [ command:

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

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