gpt4 book ai didi

bash - 通过 bash 从文件中找到最大的数字

转载 作者:行者123 更新时间:2023-11-29 09:50:43 25 4
gpt4 key购买 nike

<分区>

我想从文件中找出最大值,文件如下:

1
2
3
1
2
3
4
5
1
2
3

我的代码如下(max.sh):

#!/usr/bin/bash

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

但是当我 bash -x max.sh 时,输出是:

+ 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

看起来max取的是最大值,但为什么max的最后回显是1?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com