我的max函数抛出错误,即使它与我的min函数相同但翻转,找不到错误?



当我在脚本上运行ShellCheck时,它会给我以下错误:

Line 27:
{
^-- SC1009: The mentioned syntax error was in this brace group.
Line 30:
for in `cat popconfile`
^-- SC1073: Couldn't parse this for loop. Fix to allow more checks.
^-- SC1058: Expected 'do'.
^-- SC1072: Expected 'do'. Fix any mentioned problems and try again

脚本是:

#!/bin/bash
#getalldata() {
#find . -name "ff_*" -exec  sed -n '4p' {} ;
#}
#Defining where the population configuration file is which contains all the data
popconfile=$HOME/testarea

#Function to find the average population of all of the files
averagePopulation()
{
total=0
list=$(cat popconfile)
for var in "${list[@]}"
do
total=$((total + var))
done
average=$((total/$(${#list[*]} popconfile)))
echo "$average"
}
#Function to find the maximum population from all the files
maximumPopulation()
{
max=1
for in `cat popconfile`
do
if [[ $1 > "$max" ]]; then
max=$1
echo "$max"
fi
done
}
#Function to find the minimum population from all the files
minimumPopulation()
{
min=1000000
for in `cat popconfile`
do
if [[ $1 < "$min" ]]; then
max=$1
echo "$min"
fi
done
}
#Function to show all of the results in one place
function showAll()
{
echo "$min"
echo "$max"
echo "$average"
}

虽然我的min函数非常相似,但我没有从中得到任何错误;如果我切换minmax函数,那么首先发生的函数会报告错误。

错误只是说">预期do",但我已经有了do语句。那么错误在哪里呢?

for循环中缺少索引。立即解决的办法是

maximumPopulation()
{
max=1
for i in `cat popconfile`
do
if [[ $i > "$max" ]]; then
max=$i
echo "$max"
fi
done
}

但是,您不应该使用for循环来迭代文件的行;参见Bash FAQ 001。相反,使用while循环。

maximumPopulation () {
max=1
while IFS= read -r i; do
if (( i > max )); then
max=$i
fi
done < popconfile
printf '%dn' "$max"
}

最新更新