Sunday, December 25, 2011

Shell script to remove *~ temporary files

#************************************************#
# clean                                          #
# written by Norma Hermawan                      #
# December 25, 2011                              #
#                                                #
# Clean up temporary files.                      #
#************************************************#

usage()
{
  echo "Usage is: clean [DIR] [OPTIONS]                                            "
  echo "Remove temporary *~ files                                                  "
  echo "                                                                           "
  echo "OPTIONS:                                                                   "
  echo "    --help, -h             Show usage information                          "
  echo "    -r, -R, --recursive    remove temporary *~ files inside the directories recursively"
  echo "                                                                           "
  echo "Examples:                                                                  "
  echo "  clean ../~ -r            remove temporary *~ files inside home folder recursively"
  echo "                                                                           "
  echo "Report cat bugs to norma.hermawan@gmail.com                                "
}                                                                                 

clean-ex()
{
  found=0;
  for found in `cat temp`;
  do
    if [ -f $found ]
    then
      echo "Removed $found"
      rm $found
    fi
  done
 
  if [ $found = 0 ]
  then
    echo "Nothing to clean"
  else
    rm temp
  fi
}
     
# Main Script

  if [ "X$#" = "X0" ]
  then
    ls *~ > temp
    clean-ex
   
  elif [ "X$#" = "X1" ]
  then
    if [ "X$1" = "X-r" ] || [ "X$1" = "X-R" ] || [ "X$1" = "X-recursive" ]
    then
      find -name "*~" > temp
      clean-ex
     
    elif [ "X$1" = "X-h" ] || [ "X$1" = "X--help" ]
    then
      usage
     
    else
      ls $1\/*~ > temp
      clean-ex
     
    fi
     
  elif [ "X$#" = "X2" ]
  then
    if [ "X$2" = "X-r" ] || [ "X$2" = "X-R" ] || [ "X$1" = "X-recursive" ]
    then
      find $1 -name "*~" > temp
      clean-ex
   
    else
      echo "$0: Unknown command line option: '$2'"
    fi
   
  else
    echo "$0: Argument cannot greater than 2"
    usage
  fi 

 

No comments:

Post a Comment