Advertisement
Guest User

Bash script to verify modified date of file is within 24 hou

a guest
Nov 15th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 1.76 KB | None | 0 0
  1. #!/usr/bin/env bash
  2. #set -x
  3.  
  4. # Exit codes for OP5: 0, 1, 2 or 3 for OK, Warning, Critical or Unknown
  5.  
  6. NFS_DIR="/mnt/vol_nfs_nextgen_backup01"
  7. BACKUPS=$(find "${NFS_DIR}" -type f -iname "*.tar.gz")
  8. MAX_AGE=$(bc <<< '24*60*60')
  9. declare -A OLD_FILES
  10. declare -A ALERT
  11.  
  12.  
  13. get_file_age(){
  14.     for _FILE in $(echo "${BACKUPS}"); do
  15.         FILE_AGE=$(($(date +%s) - $(stat -c '%Y' "${_FILE}")))
  16.         FILE_NAME=$(awk -F'/' '{print $NF}' <<< "${_FILE}")
  17.  
  18.         if [[ ${FILE_AGE} -gt ${MAX_AGE} ]]; then
  19.             # An old backup was found, adding to array
  20.             FILE_AGE=$(date -d "now - ${FILE_AGE} seconds")
  21.             OLD_FILES[$_FILE]="${FILE_AGE}"
  22.         fi
  23.     done
  24. }
  25.  
  26.  
  27. find_new_files(){
  28.     for _BACKUP in "${!OLD_FILES[@]}"; do
  29.         FILE_AGE=$(($(date +%s) - $(stat -c '%Y' "${_BACKUP}")))
  30.         FILE_NAME=$(awk -F'/' '{print $NF}' <<< "${_BACKUP}")
  31.         DIR_NAME="${_BACKUP//$FILE_NAME/}"
  32.         NEW_FILES=$(find "${DIR_NAME}" -type f -mtime -1 -ls)
  33.  
  34.         if [[ ! -z "${NEW_FILES}" ]]; then
  35.             # An old backup was found and no new backups were found in the same directory, adding to alert
  36.             FILE_AGE=$(date -d "now - ${FILE_AGE} seconds")
  37.             ALERT["${DIR_NAME}${FILE_NAME}"]="${FILE_AGE}"
  38.         fi
  39.     done
  40. }
  41.  
  42.  
  43. get_file_age || exit 3
  44.  
  45. if [[ ${#OLD_FILES[@]} -gt 0 ]]; then
  46.     # An old backup was found, checking for newer backups in same directory
  47.     find_new_files || exit 3
  48.  
  49.     if [[ ${#ALERT[@]} -gt 0 ]]; then
  50.         # An old backup was found and no new backups were found in the same directory, printing alert
  51.         for x in "${!ALERT[@]}"; do
  52.             printf "%-30s %s\n" "${ALERT[$x]}" "$x"
  53.         done
  54.         exit 2
  55.     fi
  56.  
  57. else
  58.     # No issues found
  59.     exit 0
  60. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement