gpt4 book ai didi

linux - 变量在循环后失去它们的值

转载 作者:行者123 更新时间:2023-12-03 09:53:43 26 4
gpt4 key购买 nike

我有这个脚本,它应该读取每一行都有数字的文件,并显示最大的数字、最小的数字和总和。在循环期间,变量更改了它们的值,但在它们返回它们的主要值之后,我无法修复它。

#!/bin/bash

if [ ! $# -eq 1 ]; then
echo "Invalid number of arguments"
elif [ ! -e $1 ]; then
echo "File doesn't exist"
elif [ ! -s $1 ]; then
echo "File is empty"
else
min=$(head -1 $1)
max=$(head -1 $1)
sum=0
(while read i; do
(( sum+=i ))
if [ $min -gt $i ]; then
min=$i
elif [ $max -lt $i ]; then
max=$i
fi
done
)<$1
fi
echo $min $max $sum

最佳答案

(while read i; do
(( sum+=i ))
if [ $min -gt $i ]; then
min=$i
elif [ $max -lt $i ]; then
max=$i
fi
done
)<$1

通过用(包围循环引入的子shell )括号导致内部的所有变量修改都被限制在子 shell 中。子 shell 是一个子进程,子进程有自己的变量副本,与父进程的变量副本分开。

while read i; do
(( sum+=i ))
if [ $min -gt $i ]; then
min=$i
elif [ $max -lt $i ]; then
max=$i
fi
done <$1

subshel​​l 没有做任何有用的事情,所以简单的解决方案是删除它。

I changed the expression in top line of loop to cat $1|while read i and removed brackets but it didn't help.

管道和子shell有同样的问题:左右两边运行在子进程中。坚持 while ... done <file没有管道和子 shell 的版本。

关于linux - 变量在循环后失去它们的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62335044/

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