Bash Scripting,读取无限数量的整数并应用公式

时间:2016-02-18 00:34:35

标签: bash

我刚开始学习bash。我知道有解决此问题的高级方法,但我不能使用任何高级方法。我最近完成了关于循环的讲座,我希望知道如何解决这个问题。但经过3个多小时的阅读后,我无法找到解决方案。

这是提示: 通过使用位置变量创建一个脚本,该脚本将从用户(最少5个数字)中获取x个数字。然后执行以下操作:

  • 计算输入了多少个数字
  • 添加所有数字
  • 将所有数字相乘
  • 查找所有数字的平均值

read -p "Enter at least 5 integers"

#Check to make sure integers entered are indeed integers (how?)
#Check to make sure at least 5 integers were entered (how?)

#for total number of integers entered, add into a sum
#for total number of integers entered, find total product
#find average of all integers entered 

我的主要问题是检查。另外,如何为变量分配无限数量的值?谢谢你的帮助。我环顾四周,但没有找到初学者解决方案。

1 个答案:

答案 0 :(得分:1)

#!/bin/bash
declare -i sum=0
declare -i counter=0
declare -i product=1
if [[ $# -lt 5 ]]
then
    echo "Please enter atleast 5 positional parameters"
    exit 1
fi

for num in "$@"     #$@ means all positional parameters, $1, $2, $3 and so on 
do
#checking if the entered positional parameters are digits using regular expression, [0-9]+ means match any digit 1 or more times
    if [[ "$num" =~ ^[0-9]+$ ]]
    then
        sum=$(($sum+$num))
        product=$(($product*$num))
        ((counter++))
    else
        echo "$num is not a number"
    fi
done
echo 
echo "Result: "
echo "count of numbers: $counter"
echo "sum of numbers: $sum"
echo "average of numbers: "$(echo "scale=4;$sum/$counter" | bc)
echo "product of numbers: $product"

输出:

$ ./script.bash 1 2 3 4 5 abcd
abcd is not a number

Result: 
count of numbers: 5
sum of numbers: 15
average of numbers: 3.0000
product of numbers: 120

$ ./script.bash 1 2 3 
Please enter atleast 5 positional parameters

$ ./script.bash 56 78 235 67 466

Result: 
count of numbers: 5
sum of numbers: 902
average of numbers: 180.4000
product of numbers: 32048758560