Advertisement
eibgrad

compress-bash-script.sh

Mar 12th, 2015 (edited)
1,021
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.69 KB | None | 0 0
  1. #!/bin/sh
  2.  
  3. #     name: compress-bash-script.sh
  4. #  version: 4.1.1, 27-aug-2020, by eibgrad
  5. #  purpose: reduce size of bash script
  6. #    notes:
  7. #      - trailing comments are always preserved
  8. #      - output is always to stdout
  9. #      - input from stdin is optional:
  10. #          cat </path/bash-script> | compress-bash-script.sh
  11.  
  12. # --comp is the default compression level
  13. comp=
  14.  
  15. # function usage()
  16. usage() {
  17.     echo 'Usage: compress-bash-script.sh [options] [</path/bash-script>]'
  18.     echo
  19.     echo '  Reduce size of bash script.'
  20.     echo
  21.     echo '  Options:'
  22.     echo '    --nocom    remove blank lines and pure/non-functional comments'
  23.     echo '    --comp     (default) same as --nocom, plus remove leading whitespace'
  24.     echo '    -h,--help  this usage information'
  25.     echo
  26.     echo '  NOTE: If file not specifed, input is expected from stdin.'
  27.     echo
  28. }
  29.  
  30. # handle -h|--help option/argument
  31. for opt; do case $opt in -h|--help) usage; exit 0;; esac; done
  32.  
  33. # process command line options/arguments
  34. while [ $# -gt 0 ]; do
  35.     case "$1" in
  36.         --nocom) nocom=; unset comp;;
  37.          --comp) comp=; unset nocom;;
  38.               *) break 2;;
  39.     esac
  40.     shift
  41. done
  42.  
  43. if [ "$1" ]; then
  44.     if [ -f "$1" ]; then
  45.         # redirect file to stdin
  46.         exec "$0" $([ ${nocom+x} ] && echo --nocom) < "$1"
  47.     else
  48.         echo "error: file not found: $1"
  49.         exit 1
  50.     fi
  51. fi
  52.  
  53. # option nocom: remove blank lines and pure/non-functional comments
  54. [ ${nocom+x} ] && cat - | sed -r '/^[[:space:]]*($|#([[:space:]]|#|$))/d'
  55.  
  56. # option comp: same as --nocom, plus remove leading whitespace
  57. [ ${comp+x} ] && cat - | sed -r 's/^[[:space:]]*//;/^($|#([[:space:]]|#|$))/d'
  58.  
  59. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement