我的max函数抛出错误,即使它与我的min函数相同但被翻转了,找不到错误? [英] My max function is throwing an error even though its the same as my min function but flipped, can't find the error?

查看:206
本文介绍了我的max函数抛出错误,即使它与我的min函数相同但被翻转了,找不到错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

When I run ShellCheck on my script, it gives me these errors:

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函数切换到另一个位置,则会报告该最先出现的函数的错误.

Although my min function is very similar, I get no error from it; if I switch my min and max function around, then the error is reported for the function that occurs first.

错误只是说"期望的do "-但是我已经有一个do语句.那么错误在哪里呢?

The error is just saying "expected do" - but I already have a do statement. So where is the error?

推荐答案

您在for循环中缺少索引.立即修复是

You are missing the index in the for loop. The immediate fix would be

maximumPopulation()
{
max=1

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

但是,您不应该使用for循环遍历文件的行;请参阅 Bash常见问题001 .而是使用while循环.

However, you shouldn't use a for loop to iterate over the lines of a file; see Bash FAQ 001. Instead, use a while loop.

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

这篇关于我的max函数抛出错误,即使它与我的min函数相同但被翻转了,找不到错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆