tuti
tuti

Reputation: 27

Testing grep output

The cmd:

STATUS=`grep word a.log | tail -1 | awk '{print $1,$2,$7,$8,$9}'`
echo "$STATUS"

The output:

2020-05-18 09:27:01 1 of 122

I need to display this $STATUS and need to do the test comparison as well. How to compare number 122 in below? How to represent 122 in $X? The number 122 can be any number, resulted from above cmd.

 if [ "$X" -gt "300" ]
 then
  echo "$STATUS. This in HIGH queue ($X)"
 else
  echo "$STATUS. This is NORMAL ($X)"
 fi

Upvotes: 1

Views: 56

Answers (2)

Michael Back
Michael Back

Reputation: 1871

I would suggest using lowercase for variables to reduce possible confusion for someone other than the original author reading the script in the future. Also using $() is typically preferable to using back-ticks -- makes quoting easier to get right.

status="$(grep word a.log | tail -1 | awk '{print $1,$2,$7,$8,$9}')"
x="$(printf '%s' "$status" | awk '{ print $NF }')"
if [ "$x" -gt 300 ]
then
    echo "$status. This in HIGH queue ($x)"
else
    echo "$status. This is NORMAL ($x)"
fi

Note -- we could refactor the status line a bit:

status="$(awk '/word/ { x = $1 OFS $2 OFS $7 OFS $8 OFS $9 } END { print x }' a.log)"

Upvotes: 1

Freddy
Freddy

Reputation: 4688

You could do it with one awk script:

awk '
  /word/{ status=$1" "$2" "$7" "$8" "$9; x=$9 } 
  END{ printf status". This %s (%s)\n", (x>300 ? "in HIGH queue" : "is NORMAL"), x }
' a.log

Upvotes: 3

Related Questions