bash - 我的 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
功能非常相似,但我没有从中得到任何错误;如果我切换我的min
和max
功能,那么首先发生的功能会报告错误。
错误只是说“预期do
” - 但我已经有一个do
声明。那么错误在哪里呢?
解决方案
您缺少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"
}
推荐阅读
- flutter - Flutter:如何通过 onRefresh 回调传递 herotag
- yoast - 带有临时站点的 Yoast 规范问题
- javascript - React - 从子组件发布时无法让 DOM 提取最新数据
- unity3d - 在 Unity、VScode 中打开脚本时无法引用 .NetFramework
- python - 我无法使用 pip 安装 streamlit
- c# - C# 列表元组编码练习
- regex - 如果文件中的项目顺序发生更改,则正则表达式不匹配
- angular - 将 Angular 7 升级到 10 后,Angular DOM 操作中断
- android - 设置 firebase - Unity 项目 - com.google.firebase.MessagingUnityPlayerActivity & MessageForwardingService 未找到
- html - 将 Jekyll 标签分为两组