I've found awk
examples have been a big help to me. I'm adding these for myself, and others who learn by example.
#!/usr/bin/env bash
WORKFILE=$(mktemp /tmp/ssh_stats-XXXXX)
journalctl --follow --since=now | awk -v fo=$WORKFILE '/sshd:session/ && /opened/ || /sshd:session/ && /closed/ {print $0 >> fo; fflush(); }'
Notable:
- pipe
journalctl
with--follow
to awk; works as a daemon or background job - use of
-v
to pass thebash
variable$WORKFILE
toawk
- 4 pattern logic matching:
/pat1/ && /pat2/ || /pat3/ && /pat4/
to locate lines of interest - output redirect & append to file:
print $0 >> fo
- force print cache to file immediately via
fflush()
PTS_CT=$(w | awk '/pi/ && /pts/ {count++} END{print count}')
if [ $PTS_CT -gt 0 ]
then
<do something>
else
<do something else>
fi
Notable:
- Line 1: The ability to store the output of a command into a variable is called command substitution,
variable=$(commands)
and it’s one of the most useful features ofbash
. [ comparison ]
is shorthand for thebash
built-intest
;-gt
is a numerical comparisoncount++
= increment the variablecount
; it is the action executed when the patterns matchpi
&pts
in the same line/record.END
is the command executed byawk
after the last record is read.