Advertisement
justin_hanekom

rm-unneeded-files.sh

Mar 30th, 2019
252
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 6.75 KB | None | 0 0
  1. #!/bin/bash -
  2.  
  3. # File: rm-unneeded-files.sh
  4. # Copyright (c) 2018-2019 Justin Hanekom <justin_hanekom@yahoo.com>
  5. # Licensed under the MIT License
  6.  
  7. # Permission is hereby granted, free of charge, to any person obtaining
  8. # a copy of this software and associated documentation files
  9. # (the "Software"), to deal in the Software without restriction,
  10. # including without limitation the rights to use, copy, modify, merge,
  11. # publish, distribute, sublicense, and/or sell copies of the Software,
  12. # and to permit persons to whom the Software is furnished to do so,
  13. # subject to the following conditions:
  14. #
  15. # The above copyright notice and this permission notice shall be
  16. # included in all copies or substantial portions of the Software.
  17. #
  18. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  21. # IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  22. # CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  23. # TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  24. # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25.  
  26. # Setup a safe Bash scripting environment
  27.  
  28. set -o errexit      # Exit immediately if an error occurs
  29. set -o noclobber    # Do not allow files to be overwritten via redirect
  30. set -o nounset      # Do not allow unset variables
  31.  
  32. # Set the exit code of a pipeline to the rightmost non-zero on error
  33. set -o pipefail
  34. # Set the internal field separator to newline or tab, but not space
  35. IFS=$'\n\t'
  36.  
  37. # Setup a secure Bash scripting environment by: setting a secure path;
  38. # clearing all aliases; clearing the command path hash; setting the hard limit
  39. # to 0 to turn off core dumps; and setting a secure umask
  40.  
  41. PATH=$(PATH='/bin:/usr/bin' getconf PATH); export PATH
  42. builtin unalias -a
  43. hash -r
  44. ulimit -H -c 0 --
  45.  
  46. UMASK=002
  47. umask ${UMASK}
  48.  
  49. # Global constant definitions
  50.  
  51. readonly OPTIONS='d:vh'
  52. readonly LONGOPTS='directory:,verbose,help'
  53. # unneeded regexp not using --regexp='...' --regexp='...' etc.
  54. # because this would mean having to eval the grep command
  55. readonly UNNEEDED_REGEXP="\.[#].+|~$|^[#].*[#]$|\.autosave$|\.DS_Store$|\
  56. \.lein_failures$|\.lein-repl-history$|\.lisp-temp$|\.sw.$"
  57. readonly STARTED_AT=$(date '+%s')
  58.  
  59. # Global variable declarations
  60.  
  61. DIR=''
  62. IS_VERBOSE=''
  63.  
  64. ################################################################################
  65. # Function:     chomp_slash
  66. # Description:  Removes any trailing slash ("/") from a string
  67. # Arguments:    $1 :- String from which to remove any trailing slashes
  68. # Ouputs:       Prints string with trailing slashes removed
  69. function chomp_slash {
  70.     local dir="$1"
  71.     while [ "${dir:(-1)}" = '/' ]; do
  72.         dir=${dir::-1}
  73.     done
  74.     echo "${dir}"
  75. }
  76.  
  77. ################################################################################
  78. # Function:     trim
  79. # Description:  Trims any/all whitespace from the beginning and end of a string
  80. # Arguments:    $1 :- The string from which to trim whitespace
  81. # Outputs:      Prints string with any leading/trailing whitespace removed
  82. function trim {
  83.     local str="$1"
  84.     str="${str#"${str%%[![:space:]]*}"}"
  85.    str="${str%"${str##*[![:space:]]}"}"
  86.     echo "$1"
  87. }
  88.  
  89. ################################################################################
  90. # Function:     usage_exit
  91. # Description:  Prints the usage message for this script and then exits
  92. # Arguments:    $1 :- Exit code; defaults to 1
  93. # Outputs:      Prints description of how to call this script
  94. function usage_exit {
  95.     local exit_code=1
  96.  
  97.     if [[ ${1-} =~ ^[0-9]+$ ]]; then
  98.         exit_code="$1"
  99.     fi
  100.  
  101.     cat << EOT
  102. Usage: $(basename "$0") [options]...
  103.     -d|--directory  <val>   (Required) The dir containing unneccessary files
  104.     -v|--verbose            Displays verbose output
  105.     -h|--help               Displays this message and exits the script
  106.  
  107. NOTE: The <directory> argument is mandatory and *must* be supplied
  108.  
  109. EOT
  110.     exit "${exit_code}"
  111. }
  112.  
  113. ################################################################################
  114. # Function:     parse_cmd_line
  115. # Description:  Parses the command-line using the enhanced version of getopt
  116. # Arguments:    $@ :- Command-line arguments (required)
  117. # Requires:     Global variable $DIR
  118. # Outputs:      Sets above-mentioned global variable based on given
  119. #               command-line arguments
  120. function parse_cmd_line {
  121.     # Ensure that the enhanced version of getopt is available
  122.  
  123.     ! getopt --test > /dev/null
  124.     if (( "${PIPESTATUS[0]}" != 4 )); then
  125.         echo "I'm sorry, the enhanced version of getopt is required. Exiting." >&2
  126.         exit 1
  127.     fi
  128.  
  129.     # Initialize the global variables
  130.  
  131.     DIR=''
  132.     IS_VERBOSE=''
  133.  
  134.     # Parse the command-line options
  135.  
  136.     if ! readonly PARSED_OPTIONS=$(getopt --options=${OPTIONS} \
  137.                                     --longoptions=${LONGOPTS} \
  138.                                     --name "$(basename "$0")" -- "$@"); then
  139.         echo 'Unknown error parsing getopt options. Exiting.' >&2
  140.         exit 2
  141.     fi
  142.  
  143.     eval set -- "${PARSED_OPTIONS}"
  144.  
  145.     # Extract command-line options and their arguments, if any
  146.  
  147.     while (( $# >= 1 )); do
  148.         case "$1" in
  149.             -d|--directory)
  150.                 DIR="$(trim "$2")" ; shift 2
  151.                 ;;
  152.             -v|--verbose)
  153.                 IS_VERBOSE='true' ; shift
  154.                 ;;
  155.             -h|--help)
  156.                 usage_exit 0
  157.                 ;;
  158.             --)
  159.                 shift ; break
  160.                 ;;
  161.             *)
  162.                 usage_exit 3 >&2
  163.                 ;;
  164.         esac
  165.     done
  166.  
  167.     # Ensure that the required options have been supplied
  168.  
  169.     if [ -z "${DIR}" ]; then
  170.         usage_exit 4 >&2
  171.     fi
  172. } # parse_cmd_line
  173.  
  174. ################################################################################
  175. # Start of program
  176.  
  177. parse_cmd_line "$@"
  178.  
  179. # Determine what should be done when an unneeded file is found
  180.  
  181. if [ "$IS_VERBOSE" ]; then
  182.     verbose_flag='--verbose'
  183. else
  184.     verbose_flag=''
  185. fi
  186.  
  187. # Remove unneeded files
  188.  
  189. set +e  # Temporarily disable error exiting
  190. sudo find "${DIR}" -mount -path '/cdrom' -prune -path '/dev' -prune \
  191.     -path '/media' -prune -path '/root' -prune -path '/proc' -prune -print | \
  192.     grep --extended-regexp  "${UNNEEDED_REGEXP}" | \
  193.     sudo xargs rm --force ${verbose_flag}
  194. set -e  # Reenable error exiting
  195.  
  196. # Report that we are done, and how long the script took
  197.  
  198. if [ -n "$IS_VERBOSE" ]; then
  199.     readonly ENDED_AT=$(date '+%s')
  200.     readonly DIFF=$(( ENDED_AT - STARTED_AT ))
  201.     echo "Done, in ${DIFF} seconds"!
  202. fi
  203.  
  204. # vim: set filetype=sh smartindent autoindent smarttab expandtab tabstop=4 softtabstop=4 shiftwidth=4 autoread
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement