Count failed sign-ins with an array
An associative array keeps one counter for each address. This program reads a log, counts the failed sign-ins and prints the addresses, the most frequent first.
Bash, All lessons
Save these lines as panel.log
webpanel: 2026/11/24 14:00:03 192.0.2.50 failed to sign in
webpanel: 2026/11/24 14:00:06 192.0.2.50 failed to sign in
webpanel: 2026/11/24 14:00:07 192.0.2.71 signed in
webpanel: 2026/11/24 14:00:09 192.0.2.50 failed to sign in
webpanel: 2026/11/24 14:02:41 192.0.2.18 failed to sign in
webpanel: 2026/11/24 14:02:44 192.0.2.18 failed to sign inSave the program as count.sh
#!/usr/bin/env bash
# Count failed sign-ins by address.
set -euo pipefail
log=${1:?Usage: count.sh LOGFILE}
declare -A fails
while read -r _ day time addr rest; do
[[ $rest == "failed to sign in" ]] || continue
fails[$addr]=$(( ${fails[$addr]:-0} + 1 ))
done < "$log"
for addr in "${!fails[@]}"; do
printf '%4d %s\n' "${fails[$addr]}" "$addr"
done | sort -rnRun it
bash count.sh panel.logThe output
3 192.0.2.50
2 192.0.2.18Try it yourself
Change the program so that it prints only addresses with three or more failed sign-ins.
Add a test before printf:
(( fails[$addr] >= 3 )) || continueYou need Bash 4 or later. TurboShell installs Bash 5.3.
Notes to the lines
- 3Bash stops at the first error, at a variable that has no value and at an error inside a pipe.
- 5The first argument is the log file. Without it the program prints the usage line and stops.
- 6
declare -Amakes an associative array. Its keys are text: here, addresses. - 8–10
readsplits each line at the spaces. A line that does not end in “failed to sign in” is skipped. - 10
:-0gives 0 the first time an address appears. - 13–15
${!fails[@]}lists the keys.sort -rnputs the largest number first.