misskelly has asked for the wisdom of the Perl Monks concerning the following question:

Hello all: I'm looking for a script that finds broken symlinks in unix and removes them. No luck as of yet. Does anybody have any ideas? Thx

Replies are listed 'Best First'.
Re: Broken symlinks
by chipmunk (Parson) on Feb 16, 2001 at 02:20 UTC
    I was finishing up a solution using File::Find when I happened to look through the module's documentation, to make sure I was doing everything properly, and I found this example:
    sub wanted { -l && !-e && print "bogus link: $File::Find::name\n"; }
    Anyway, here's a solution that actually removes the broken symlinks:
    use File::Find; find(\&remove_broken_symlinks, '/path/to/start'); sub remove_broken_symlinks { if (-l && !-e) { print "Removing broken symlink: $File::Find::name\n"; unlink($_) or die "Can't unlink $File::Find::name: $!\n"; } }
Re: Broken symlinks
by merlyn (Sage) on Feb 16, 2001 at 03:04 UTC
Re: Broken symlinks
by KM (Priest) on Feb 16, 2001 at 02:14 UTC
    perldoc -f readlink

    Look at perldoc -f readder (and opendir) for the directory traversal (or File::Find, or your favorite way to snarf filenames). Then, for each file you could do something like:

    ... stuff to get filename .. .. loop through those files.. for my $file (@files) { my $link = readlink($file) || "Fooey"; if ($link ne "Fooey") { if (-e $link) { print "symlink OK, moving on"; }else{ unlink $file; } } }

    You get the idea :)

    Cheers,
    KM

Re: Broken symlinks
by misskelly (Initiate) on Feb 21, 2001 at 01:37 UTC
    Thank you all for your help!!! :)