Last active
July 15, 2025 20:07
-
-
Save msmafra/d7ec6acfcf1ff2ba772935424c9cfc94 to your computer and use it in GitHub Desktop.
Based on Bash Scripting Tutorial for Beginners by Nana https://www.youtube.com/watch?v=PNhq_4d-5ek
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
nanalyse_logs() { | |
# always good to declare the variable with declare here, or local inside a function | |
local LOG_DIR | |
local -a ERROR_PATTERNS #set it as an array since the start | |
local REPORT_FILE | |
local -a LOG_FILES # set it as an array since the start | |
local PATTERN_LIST | |
local WHEN | |
LOG_DIR="${HOME}/Downloads/Nana-youtube" | |
ERROR_PATTERNS=( | |
"ERROR" | |
"FATAL" | |
"CRITICAL" | |
) | |
# as te reports would be daily using just Y-m-d format | |
WHEN="$(date '+%F')" | |
# not recommended to be in the same directory, but for the example is good | |
REPORT_FILE="${LOG_DIR}/log_analysis_report-${WHEN}.txt" | |
# mapfile or readarray to store the found files in side the array | |
mapfile -t LOG_FILES < <(find "${LOG_DIR}" -name "*.log" -mtime -1) | |
# | |
printf "%s\n%s\n" "Analysing log files" "==============" | tee --append "${REPORT_FILE}" | |
printf "%s\n" "List of log files updated in last 24 hours" | tee --append "${REPORT_FILE}" | |
for LF in "${!LOG_FILES[@]}"; do | |
printf "\t%s - %s\n" "$((LF+1))" "${LOG_FILES[LF]}" | tee --append "${REPORT_FILE}" | |
done | |
for LOG_FILE in "${LOG_FILES[@]}"; do | |
# printf "\n%s\n" | |
for PATTERN in "${ERROR_PATTERNS[@]}"; do | |
PATTERN_LIST="$(grep --fixed-strings "${PATTERN}" "${LOG_FILE}")" | |
printf "\nSearching %s logs in %s file...\n" "${PATTERN}" "${LOG_FILE}" | tee --append "${REPORT_FILE}" | |
printf "%s\n" "${PATTERN_LIST}" | tee --append "${REPORT_FILE}" | |
printf "Number of %s logs found in %s file is: %s\n" "${PATTERN}" "${LOG_FILE}" "${#PATTERN_LIST}" | tee --append "${REPORT_FILE}" | |
if [[ "${#PATTERN_LIST}" -gt 10 ]];then | |
printf "\n ⚠ ACTION REQUIRED: too many %s issues (%s) in log file %s.\n" "${PATTERN}" "${#PATTERN_LIST}" "${LOG_FILE}" | |
fi | |
unset PATTERN_LIST | |
done | |
done | |
} | |
nanalyse_logs || return 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment