BASH script, !=: command not found

1.5k views Asked by At

Getting the error above when running my script. Trying to check if the value of output is not = to "average:". If not, then print to list file, if it is then start from beginning of loop.

#!/bin/bash

Oad=$(date +%Y_%m_%d.%H.%M.%S)

for i in {1..120}
do
OUTP= uptime | awk '{print $10}' | cut -f1 -d, 
echo $OUTP
if $OUTP != average:
   then $OUTP >> $Oad.lst
else continue;
fi
sleep 60
done
cat $Oad.lst | awk '{if(min==""){min=max=$1}; if($1>max) {max=$1}; if($1<min) {min=$1}; total+=$1; count+=1} END {print total/count, max, min}' > $Oad.out
2

There are 2 answers

1
konsolebox On BEST ANSWER

That's not the way to compare it.

if $OUTP != average:

Should be

if [[ $OUTP != average: ]]

Some line seemed odd as well

OUTP= uptime | awk '{print $10}' | cut -f1 -d,

I think should be

OUTP=$(uptime | awk '{print $10}' | cut -f1 -d,)

And

then $OUTP >> $Oad.lst

if you want to send the value of the variable to the file, it should be

then echo "$OUTP" >> "$Oad.lst"

Overall I would suggest a format like this:

#!/bin/bash

Oad=$(date +%Y_%m_%d.%H.%M.%S)

for i in {1..120}; do
    OUTP=$(uptime | awk '{print $10}' | cut -f1 -d,)
    echo "$OUTP"
    if [[ $OUTP != average: ]]; then
        echo "$OUTP" >> "$Oad.lst"
        sleep 60
    fi
done

awk '{if(min==""){min=max=$1}; if($1>max) {max=$1}; if($1<min) {min=$1}; total+=$1; count+=1} END {print total/count, max, min}' "$Oad.lst" > "$Oad.out"

One more note. For:

    if [[ $OUTP != average: ]]; then

You probably mean it as:

    if [[ $OUTP != *average:* ]]; then

To match any line not containing average: instead of any line that's not exactly like it.

0
tripleee On

This is just a side comment to augment @konsolebox' answer, but it might be better still to do all of the logic in a single Awk script.

#!/bin/bash

Oad=$(date +%Y_%m_%d.%H.%M.%S)

for i in {1..120}
do
    uptime
    sleep 60
done |

awk '$10 != "average" { t=$10; sub(/,.*/,"",t);
         if(min=="") min=max=t;
         if(t>max) max=t;
         if(t<min) min=t;
         total += t; count++ }
    END {print total/count, max, min}' > $Oad.out

This requires some refactoring if you also want the intermediate results in $Oad.lst, but it's not an intrusive change. (Just print in the main loop, and open a second file handle in the END loop.)