Find dead softlink files by shell

Symbolic linked files are commonly used in Linux system. For example some service inital scripts are stored in /etc/init.d and linked to /etc/rc0.d, /etc/rc1.d, /etc/rc2.d, /etc/rc3.d, /etc/rc4.d, /etc/rc5.d and /etc/rc6.d, so that the system is able to control related services in different runlevel.

But sometimes if the symlink files got broken, how can we find the dead ones out?

Here’s a simple script does the work well:

[planet@admon ~]$ cat check-dead-softlink.sh

[planet@admon ~]$ cat check-dead-softlink.sh
#!/bin/bash
#
# joseph from https://www.admon.org
# This script is intended to find broken symlinks for
# a list of specified directories.

[ $# -eq 0 ] && directorys=`pwd` || directorys=$@

linkchk()
{
        for file in $1/*
        do
        [ -L "$file" -a ! -e "$file" ] && echo "$file"
        [ -d "$file" ]&&linkchk $file
        done
}

for directory in $directorys
do
    [ -d $directory ] && linkchk $directory
  else
    echo "$directory is not a directory, request ignored!"
    echo "Usage: $0 dir1 dir2 dir3 ..."
  fi
done
exit 0

The output from an examining case:

[planet@admon ~]$ cd shell/
[planet@admon shell]$ ls -l symbol
lrwxrwxrwx 1 root root 28 Oct 10 15:19 symbol -> /home/oracle/hldataadmin.dmp
[planet@admon shell]$ cat symbol
cat: symbol: No such file or directory
[planet@admon shell]$ cd ..
[planet@admon ~]$ ./check-dead-softlink.sh shell
"shell/symbol"

If you face any issues on this script, please dont hesitate to create a post here at Linux Scripting at Forum.Admon.org

Share Button

Leave a comment

Your email address will not be published. Required fields are marked *