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
journalctlwith--followto awk; works as a daemon or background job - use of
-vto pass thebashvariable$WORKFILEtoawk - 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>
fiNotable:
- 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 thebashbuilt-intest;-gtis a numerical comparisoncount++= increment the variablecount; it is the action executed when the patterns matchpi&ptsin the same line/record.ENDis the command executed byawkafter the last record is read.