首页 > 解决方案 > 我的 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声明。那么错误在哪里呢?

标签: bashunixmaxmin

解决方案


您缺少for循环中的索引。立即修复将是

maximumPopulation()
{
max=1

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

但是,您不应该使用for循环来遍历文件的行。请参阅Bash 常见问题解答 001。相反,使用while循环。

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

推荐阅读