Advertisement
Darker666

Validate symbolic link bash

Apr 21st, 2015
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.49 KB | None | 0 0
  1. # Validates link given by path returns 1 if it's invalid.
  2. # Invalid link's absolute paths will also be forwarded to stdout.
  3. #  first parameter must be path
  4. #  after path, flags can follow:
  5. #    -r --remove     remove invalid link immediatelly
  6. #    -a --all        print given absolute link path on the stdout even if it's valid.
  7. validatelink() {
  8.   # dbg "Param \$0: $0"
  9.   # dbg "Param \$1: $1"
  10.   # dbg "Param \$2: $2"
  11.   #while read line ; do
  12.   #  echo "LINK: $line";
  13.   #
  14.   #; done
  15.   linkpath=$(abspath $1);
  16.   shift;
  17.   REMOVE=false;
  18.   ALL=false;
  19.   # This while finds any -flags that can be set
  20.   while [[ $# > 0 ]]
  21.   do
  22.     key="$1"
  23.     # dbg "Checking param: \"$key\"";
  24.     case $key in
  25.         -r|--remove)
  26.         REMOVE=true;
  27.         # dbg "  Remove enabled";
  28.         ;;
  29.         -a|--all)
  30.         ALL=true;
  31.         ;;
  32.         *)
  33.           # dbg "   WARNING: Unknown parameter \"$key\"";
  34.         ;;
  35.     esac
  36.     shift
  37.   done
  38.  
  39.   # Path will now contain link target path
  40.   dbg "LINK: $linkpath";
  41.   path=$(readlink -n -s -f $linkpath);
  42.  
  43.  
  44.   # -f checks if file exists
  45.   if ! [ -f $path ] && ! [ -d $path ]; then
  46.     echo "$linkpath"
  47.     dbg "  => File $path doesn't exist"
  48.     if [ "$REMOVE" = true ]; then
  49.       dbg "   - Removing this nasty file."
  50.       rm "$linkpath"
  51.     fi
  52.     return 1;
  53.   else
  54.     if [ "$ALL" = true ]; then
  55.       dbg "Print valid link: " --nonewline
  56.       echo "$linkpath"
  57.     else
  58.       dbg "  => File: $path"
  59.     fi
  60.     return 0;
  61.   fi
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement