logrotate 994 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #!/bin/bash
  2. ## Simple logrotate script
  3. ## http://superglue.it | Danja Vasiliev, 2014
  4. ##
  5. ## Takes filepath or file mask as argument:
  6. ## logrotate /www/access.log [/www/error*.log]
  7. ## and gzip compresses them inplace
  8. ## default settings
  9. ## override in config file mentioned below
  10. _ROTATE=30 ## backlogs to keep, days
  11. _DATE=$(date +%d.%m.%y-%H:%M:%S)
  12. _LOGS=( $* )
  13. ## read config file
  14. _CONF='/etc/logrotate.conf'
  15. [[ -e $_CONF ]] && . $_CONF
  16. function err {
  17. local _ERR=$?
  18. printf %s": "%s"\n" "$(basename $0)" "$1"
  19. exit $_ERR
  20. }
  21. [[ -n $_LOGS ]] || err 'missing input file'
  22. [[ -e $_LOGS ]] || err 'input file not readable'
  23. for _FILE in ${_LOGS[@]}; do
  24. ## get number of backlogs and purge unwanted
  25. _NUM=( $(ls -1 -r $_FILE*.gz &>/dev/null || echo '') )
  26. [[ ${#_NUM[@]} -gt $((_ROTATE-1)) ]] && rm -f ${_NUM[@]:$((_ROTATE-1)) }
  27. ## compress and move
  28. gzip -f $_FILE || err 'failed to gzip file'
  29. mv $_FILE.gz "$_FILE"-"$_DATE".gz || err 'failed to rename archive'
  30. done
  31. exit $?