2

I would like to find the biggest value from the file, and the file is as below:

1
2
3
1
2
3
4
5
1
2
3

my code is as below(max.sh):

#!/usr/bin/bash

max=1
cat ./num | while read line; do
    if [ $line -gt $max ]; then
        max=$line
    fi
done
echo $max

but when I bash -x max.sh, the output is:

+ max=1
+ cat ./num
+ read line
+ '[' 1 -gt 1 ']'
+ read line
+ '[' 2 -gt 1 ']'
+ max=2
+ read line
+ '[' 3 -gt 2 ']'
+ max=3
+ read line
+ '[' 1 -gt 3 ']'
+ read line
+ '[' 2 -gt 3 ']'
+ read line
+ '[' 3 -gt 3 ']'
+ read line
+ '[' 4 -gt 3 ']'
+ max=4
+ read line
+ '[' 5 -gt 4 ']'
+ max=5
+ read line
+ '[' 1 -gt 5 ']'
+ read line
+ '[' 2 -gt 5 ']'
+ read line
+ '[' 3 -gt 5 ']'
+ read line
+ echo 1
1

it looks the max get the biggest value, but why the last echo of max is 1?

1 Answers1

3

You are getting value of 1 because you are using an unnecessary pipeline which is making while loop executing in a sub-shell hence value of max getting lost in child shell itself and you get preset value of 1 in parent shell after loop.

It is better to use awk for this:

awk 'min == "" || $1<min{min=$1} $1>max{max=$1} END{print min, max}' file

5
anubhava
  • 761,203
  • 64
  • 569
  • 643