Differences between revisions 3 and 4
Revision 3 as of 2009-02-10 15:55:01
Size: 799
Editor: NeilMoore
Comment: don't use [ -a ], since Posix leaves the behaviour of test unspecified when there are more than four arguments
Revision 4 as of 2010-10-15 22:08:03
Size: 1040
Editor: WillDye
Comment: Make the expression & explanation a bit easier (IMO) for newbies to read
Deletions are marked like this. Additions are marked like this.
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.
Line 14: Line 22:
POSIX has these same tests, with the same semantics, so it can also be done with the `[` command: POSIX has these same tests, with similar semantics,
so if for some reason you can't use the (preferred) `[[` command,
the same tes
t can be done using the older `[` command:
Line 18: Line 28:
if [ -L "$symlink" ] && [ ! -e "$symlink" ]; then
 
echo "$symlink is dangling"
if [ -L "$name" ] && [ ! -e "$name" ]
then echo "$name is a dangling symlink"

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)