I’m monitoring from an actively written to file:
My current solution is:
ws_trans=0 sc_trans=0 tail -F /var/log/file.log | while read LINE echo $LINE | grep -q -e "enterpriseID:" if [ $? = 0 ] then ((ws_trans++)) fi echo $LINE | grep -q -e "sc_ID:" if [ $? = 0 ] then ((sc_trans++)) fi printf "r WSTRANS: $ws_trans tt SCTRANS: $sc_trans" done
However when attempting to do this with AWK I don’t get the output – the $ws_trans and $sc_trans remains 0
ws_trans=0
sc_trans=0
tail -F /var/log/file.log |
while read LINE
echo $LINE | awk '/enterpriseID:/ {++ws_trans} END {print | ws_trans}'
echo $LINE | awk '/sc_ID:/ {++sc_trans} END {print | sc_trans}'
printf "r WSTRANS: $ws_trans tt SCTRANS: $sc_trans"
done
Attempting to do this to reduce load. I understand that AWK doesn’t deal with bash variables, and it can get quite confusing, but the only reference I found is a non tail application of AWK.
How can I assign the AWK Variable to the bash ws_trans and sc_trans? Is there a better solution? (There are other search terms being monitored.)
Advertisement
Answer
You need to pass the variables using the option -v, for example:
$ var=0
$ printf %d\n {1..10} | awk -v awk_var=${var} '{++awk_var} {print awk_var}'
To set the variable “back” you could use declare, for example:
$ declare $(printf %d\n {1..10} | awk -v awk_var=${var} '{++awk_var} END {print "var=" awk_var}')
$ echo $var
$ 10
Your script could be rewritten like this:
ws_trans=0
sc_trans=0
tail -F /var/log/system.log |
while read LINE
do
declare $(echo $LINE | awk -v ws=${ws_trans} '/enterpriseID:/ {++ws} END {print "ws_trans="ws}')
declare $(echo $LINE | awk -v sc=${sc_trans} '/sc_ID:/ {++sc} END {print "sc_trans="sc}')
printf "r WSTRANS: $ws_trans tt SCTRANS: $sc_trans"
done