awk issue when trying to sort variables with same values

Written by - 0 comments

Published on - Listed in Linux Shell Coding

One month ago I wrote about a possibility how to "Use bash to compare remote cpu load and print lowest value of array".

Today I encountered an issue with exactly this command:

# for server in server01 server02 server03 server04; do
  case $server in
    server01) load[1]=$(ssh root@$server "cat /proc/loadavg | awk '{print \$3}'");;
    server02) load[2]=$(ssh root@$server "cat /proc/loadavg | awk '{print \$3}'");;
    server03) load[3]=$(ssh root@$server "cat /proc/loadavg | awk '{print \$3}'");;
    server04) load[4]=$(ssh root@$server "cat /proc/loadavg | awk '{print \$3}'");;

# echo "${load[*]}" | tr ' ' '\n' | awk 'NR==1{min=$0}NR>1 && $1<min{min=$1;pos=NR}END{print pos}'


The returned position was not shown - just an empty line was returned.
Why's that? Let's take a look at all the values in the array "load":

# echo "${load[*]}"
0.05 0.05 0.05 0.05

So all array values have the exact same value. awk can't therefore define the lowest value.

The solution to this is to do a "lower or equal" comparison (note the "<="):

# echo "${load[*]}" | tr ' ' '\n' | awk 'NR==1{min=$0}NR>1 && $1<=min{min=$1;pos=NR}END{print pos}'

When all values are the same, awk will end up returning the position of the last found value.

Add a comment

Show form to leave a comment

Comments (newest first)

No comments yet.