My max function is throwing an error even though its the same as my min function but flipped, can't find the error?

半城伤御伤魂 提交于 2019-12-13 03:56:49

问题


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

The script is:

#!/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"
}

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.

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


回答1:


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
}

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"
}


来源:https://stackoverflow.com/questions/51263677/my-max-function-is-throwing-an-error-even-though-its-the-same-as-my-min-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!