Search code examples
if-statementawk

Using awk and if statement


I need to use an AWK command to do a compare against 2 numbers. if 1 number is higher the the other then Fire a Command. The unix shell is very stripped down but does support awk. I am new to this and need a little help.

I have tried a bunch of different ways. I dont know what I am missing.

if (awk '{$1 > 80}' $OUTPUT3) echo 'FireActions' else fi

So if the number in the variable $OUTPUT3 is higher then 80, fire actions. Otherwise ignore.

Currently no actions fire.


Solution

  • awk is a little awkward for this particular case. You need to return 0 to indicate success, and non-zero to indicate failure, which inverts the boolean 0 == false and 1 == true. But it's not too bad:

    if awk 'END{ exit !($1 > 80)}' $OUTPUT3; then echo 'FireActions'; else ...; fi
    

    The above assume $OUTPUT3 contains the name of an input file, which does not appear to be what you want. If you just want to know if $OUTPUT3 is greater than 80, awk is the wrong tool. You want

    if test "$OUTPUT3" -gt 80; then ...; fi
    

    If for some reason you really want to use awk, you could do:

    if echo $OUTPUT3 | awk 'END{ exit !($1 > 80)}'; then echo 'FireActions'; fi 
    

    or

    if awk 'END{ exit !(c > 80)}' c="$OUTPUT3" < /dev/null ; then echo 'FireActions'; fi